- Home /
2D Rotation for aiming problem
Hi, I'm having a bit of trouble wrapping my head around this at the minute... I'm trying to get an aiming function working for my AI in a 2D top-down game (I'm using orthello, if that matters), currently I have this code:
float planeDif = target.transform.position.z - this.transform.position.z;
Vector3 worldTargetPos = (target.position - transform.position);
worldTargetPos.z = planeDif;
worldTargetPos = Camera.main.ScreenToWorldPoint(worldTargetPos);
direction = -worldTargetPos.normalized;//I did this because otherwise the up/down aiming goes in the opposite direction (eg: char moves up, AI aims down)
lookRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * rotationSpeed);
This seems to track my character properly if I move up and down, but moving left and right messes everything up, if I move left it aims way down and if I move right it aims way up. I've tried playing around with rotation values and such but I can't get it to work and now im sort of stuck in a rut...any help would be appreciated.
Answer by robertbu · Aug 19, 2013 at 04:10 PM
You are doing a ScreenToWorldPoint() translation of a point that is already in world space. If I understand your code correctly, you are trying to get the object this script is a component of to point at the target in a top down game. If so, then you should be doing something like:
Vector3 direction = (target.position - transform.position);
direction.y = 0.0f;
Quaternion lookRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * rotationSpeed);
The 'direction.y = 0.0' makes sure the rotation stays 2D. If everything is a on a plane at the same 'y' value, it is not necessary.
This works perfectly, I had something like this before but it wasn't working properly, I just looked again and it was just because the base rotation of the game object was off, I only had to correct it by 90 degrees and it works great, thanks for your help !
Your answer
Follow this Question
Related Questions
How to Rotate Editor Camera in 2D? 1 Answer
Look for the player isn't working 1 Answer
Help with 2D topdown combat 1 Answer