Akash Agarwal
Akash Agarwal

Reputation: 2530

Shoot projectile at exact angle

I'm trying to develop a simple shooting mechanism which instantiates a 'shot' based on the angle of rotation of the shooter. My problem here is even though the shooter is oriented at 0*, the shot fires at an angle of 45*(this is what I'm guessing the problem is because when the shooter is oriented at 45*, the shot is fired at exact 90*).

Shooter angle(0,0,0)

enter image description here

Shooter angle(0,0,45)

enter image description here

Note- The ball always launches from the center of the black flattened cylinder object.

Required Code:

public class ShotMoveScript : MonoBehaviour {
    public static float xForce;
    public Transform shott;
    void Update () {
        if(Input.GetKey(KeyCode.Q))
        {
            transform.Rotate(Vector3.forward, 5f);
        }

        if(Input.GetKey(KeyCode.E))
        {
            transform.Rotate(Vector3.forward, -5f);
        }

        if(Input.GetKey(KeyCode.Space))
        {
            xForce += 0.2f;
        }

        if(Input.GetKeyUp(KeyCode.Space))
        {
            Instantiate(shott, transform.position, transform.rotation);
        }

    }
}

Script attached to the ball which gets instantiated:

public class MovementScript : MonoBehaviour {
    void Update () {
        Rigidbody2D rb;
        rb = GetComponent<Rigidbody2D> ();
        rb.gravityScale = 0.8f;
        transform.Translate( new Vector3(1,1,0) * ShotMoveScript.xForce * Time.deltaTime, Space.Self);
    }
}

Upvotes: 0

Views: 1230

Answers (1)

Skyblade
Skyblade

Reputation: 2383

You rotate the ball when instantiating it with the third parameter rotation (see reference). After that you apply a Vector pointing to (1, 1) so the ball will move along that direction relative to his local rotation.

Either pass Quaternion.identity as the third parameter to Instantiate method or move the ball along (1, 0) direction.

Upvotes: 1

Related Questions