- Home /
The question is answered, right answer was accepted
How can I get local 2d Velocity?
Hello, I have this script that is supposed to be attached to an enemy. Then, the enemy must look at the player and walk onto him. The problem is that the enemy is looking at the player, but he constantly goes up, and not towards the player. Any help??
function Update() {
//Pl is the variable for player gameobject.
var dir = pl.transform.position - transform.position;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - 90;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
//walk to player
rigidbody2D.velocity = new Vector2(0, Mathf.Lerp(0, speed, 0.8f));
}
EDIT: I found a solution:
rigidbody2D.velocity = transform.TransformDirection(Vector2(0,Mathf.Lerp(0, speed, 0.8f)));
Answer by robertbu · Nov 30, 2014 at 04:06 PM
The -90 probably means you constructed your sprite so that the 'front' of the sprite is facing down when the rotation is (0,0,0). Typically a sprite is constructed so that the front is facing right with rotation (0,0,0), eliminating the '-90'. So you can walk the direction you are facing (down) by changing the last line to:
rigidbody2D.velocity = -transform.up * speed;
$$anonymous$$y sprite is wrong, I have the "-90" because it actually walks on his right side, in front.
Answer by static_cast · Nov 30, 2014 at 03:52 PM
Use rigidbody2D.velocity.magnitude
to read the veolcity.
Use Vector2.Lerp(transform.position, yourPlayer.transform.position, 0.5f);
to lerp towards the player.