1
\$\begingroup\$

I'm trying to get the player to shoot a projectile at the mouse position, however the projectile is shot in weird directions (http://gfycat.com/BothFluidHoneyeater).

Here is relevant part of my code:

var shotSpeed = 1000;
var projectile : Rigidbody;

function Update () {
    var clone : Rigidbody;
    if(Input.GetKeyDown(KeyCode.Mouse0)){
        clone = Instantiate(projectile, transform.position, transform.rotation);
    }
    clone.rigidbody.AddForce(Vector3.forward * shotSpeed);
}

What am I doing wrong?

\$\endgroup\$
4
  • \$\begingroup\$ If you set(and lock) camera to top view, does this problem still occur? \$\endgroup\$
    – wondra
    Commented Sep 11, 2014 at 12:43
  • \$\begingroup\$ It's a relevant part, but you don't show where you set the transform.position and (more importantly) transform.rotation, as is, the reason it doesn't instantiate at mouse position is because you're telling it to instantiate at transform.position. \$\endgroup\$
    – Elva
    Commented Sep 11, 2014 at 13:08
  • \$\begingroup\$ @KevinvanderVelden That's because I want it to launch toward the mouse position, not start at the mouse position. I should have phrased it simpler; I want to shoot in the direction the player is facing, as the player faces the mouse. \$\endgroup\$
    – eren_tetik
    Commented Sep 11, 2014 at 13:13
  • 2
    \$\begingroup\$ Well then your title is wrong =p. Still doesn't change my point that you're not showing the important bit of code. \$\endgroup\$
    – Elva
    Commented Sep 11, 2014 at 13:45

1 Answer 1

1
\$\begingroup\$

First off, you should only be applying forces to rigid bodies inside the FixedUpdate method. You'll get more consistent results.

If you want objects to move in the direction another object is facing, you need to use transform.forward, not Vector3.forward. Alternatively you can multiply Vector3.forward by the quaternion of the rotation you want to use, like transform.rotation * Vector3.forward, this will output a Vector3 that's been rotated to face the same direction as the rotation you supplied.

The last thing to check is that your projectiles aren't colliding with the parent body that's spawning them. Since you're spawning the projectiles inside the parent body, you need to ensure they're not colliding, as that would produce strange results.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .