How to make a 2D sprite rotate towards a specific point while facing perpendicular to the camera ?
So I am creating a 2D project.I want my 2D sprite worm to rotate in the direction of a specific point(for eg the football sprite) in my game plane . I tried using LookRotation but the problem is the worm is not facing perpendicular to the camera so it is not visible in 2D view . My game plane is X-Y plane . When I run it , it looks like this -
Notice that the worm is not visible . Here is the 3D view -
This is the code I used :
Vector3 relativePos = target.transform.position - worm.transform.position;
Quaternion rotation=Quaternion.LookRotation (relativePos);
worm.transform.rotation = rotation;
Also , changing the upward direction ,like setting it to vector3.forward , is not helping . Please help , I am stuck here ! I will be grateful to you !
Answer by Scribe · Mar 30, 2018 at 07:09 PM
This is a definitely a good time to use Quaternion.LookRotation, unfortunately the way you want to specify the directions is a bit convoluted because of the orientation that you want.
The inmortant bit to notice is that you want the forward direction (the worms blue axis) to oint at the camera, which I have assumed is in the direction -Vector3.forward
(on the penultimate line), and the up direction is not straight up, we have to calculate oour up direction by knowing it is perpendicular (at right angles to) the relativePos
vector that you calculated. The following is untested but it should give you something to go on, this might help understanding
Vector3 relativePos = target.transform.position - worm.transform.position;
// get the desired up vector by finding the vector perpendicular to relativePos
// and make sure we have a positive y value
// the following works because if y is going to be negative then Mathf.Sign is -1 and so inverts the vector
// otherwise it does nothing
Vector3 desiredUp = new Vector3(relativePos.y, -relativePos.x, 0) * Mathf.Sign(-relativePos.x);
Quaternion rotation = Quaternion.LookRotation (-Vector3.forward, desiredUp);
worm.transform.rotation = rotation;
Hope that helps!
Thanks for your help , although I already found the solution by another method .
Your answer
Follow this Question
Related Questions
Something seriously weird is going on with my transform.eulerAngles 0 Answers
Problem with Quaternion and Euler Angles 0 Answers
Draw a ray from a gamobject and keep direction of the ray relative to the gameobjects rotation. 1 Answer
Rotating an Object (To Face Another Object) Only on X and Y Axis 3 Answers