- Home /
2D AI, Aim at player - even when jumping?
Guys I'm looking for a way to do essentially what LookAt() would do in 3D, my issue is the enemy is about two times taller than the player, the player can jump and the enemy is supposed to shoot at them (or patrol etc. etc.)
Any ideas?
Short&Clear: Shoot at the player, even while jumping using an Instantiation and AddForce() or alternatively Translate, with preference to the former.
I'd post the code I have so far but it'll just make things messy essentially: If player not inside a trigger - move otherwise, Stop and shoot.
Answer by robertbu · Apr 19, 2014 at 08:57 PM
The "LookAt" for 2D would be something like this:
var dir = player.position - transform.position;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
This code assumes that with rotation (0,0,0) the AI is facing right. If the AI faces up, then add 90 to the angle before calling AngleAxis()
After you've rotated the projectile, you can use AddForce() using the projectiles transform.right or transform.up (depending on the natural orientation of the projectile).
Ugh, unfortunately I can't up-vote quite yet. I will put this to use tomorrow. Thanks a bunch.
Your answer
Follow this Question
Related Questions
[I REALLY NEED HELP FAST]Help with enemy Shooting 1 Answer
Check lenght from player? 2 Answers
Enemy keeps moving in one direction. Help pls! 2 Answers
EnemyAI C# Error 1 Answer
OnTriggerEnter2D with multiple objects 0 Answers