- Home /
magnitude normalize help
hi i am making a 2d shooting and i have a enemy script that i don't really understand here is the code
var enemy : Transform; var speed : float = 10;
function Update () { var target : Vector3 = enemy.position; var moveDirection : Vector3 = target - transform.position; var velocity = rigidbody.velocity;
if(moveDirection.magnitude < 1){
velocity = Vector3.zero;
}
else{
velocity = moveDirection.normalized * speed;
}
rigidbody.velocity = velocity;
}
i copied it from a tutorial and i am pretty new in unity so can someone tell me how to change this script so that the object only tracks on the x axis?
Answer by duck · May 17, 2010 at 05:09 PM
To restrict the motion to a certain plane or axis, you just need to zero-out the values for the other axes in your 'moveDirection' variable. So, immediately after the line which says:
var moveDirection : Vector3 = target - transform.position;
You could have, for example:
// restrict moveDirection to X only
moveDirection.y = 0;
moveDirection.z = 0;
or:
// restrict moveDirection to X-Z plane:
moveDirection.y = 0;
ok i tried it and it seems to make the attached rigidbodys gravity to not work right.
well yes - you're setting the rigidbody's velocity directly, this will override the gravity. (your original code would have too).
You'll need to use a method other than setting the velocity directly if you want gravity to be able to have an effect.