Search code examples
c#unity-game-engineangle

Change projectile angle


I'm trying to add accuracy to my game. Currently my player will always fire directly ahead (which is pointing towards the mouse cursor). I would like to offset that firing angle by x degrees.

My firing script currently looks like this :

nextFire = Time.time + bulletConfig.TimeBetweenShots;
var offset = new Vector3(0, 0, 0);
var grid = GameObject.FindObjectOfType<Grid>();
var proj = Instantiate(projectile, transform.position, Quaternion.identity, grid.transform);
proj.transform.position = transform.position + offset;
proj.transform.rotation = transform.rotation;
print(proj.transform.rotation);

var controller = proj.GetComponent<BulletController>();
if (controller != null)
{
    controller.Fire(bulletConfig);
}

Destroy(proj, bulletConfig.DestroyTime);

The core of my problem is that I don't know how to add degrees to a vector3, without some complicated trigonometry.

Any ideas?


Solution

  • As mentioned in the comment:

    The documentation for Transform.rotate state: "To rotate an object, use Transform.Rotate."

    Modifying your example this would look like this:

    // -- snipped for brevity
    var proj = Instantiate(projectile, transform.position, Quaternion.identity, grid.transform);
    proj.transform.position = transform.position + offset;
    proj.transform.rotation = transform.rotation;
    // Using the second overload of Transform.Rotate
    float exampleOffsetAngle = 1.0f;
    proj.transform.Rotate(exampleOffsetAngle, 0.0f, 0.0f);
    print(proj.transform.rotation);
    // -- snipped for brevity
    

    For more examples and usage of the other overloads please refer to the official docs: https://docs.unity3d.com/ScriptReference/Transform.Rotate.html