- Home /
Sprite "face" second sprite only on Z axis
Hello everyone. Im trying to make my sprite "face" another sprite (rotate on the Z axis to face it ingame).
And i tried using LookAt, but then it rotates on X & Y axis.
I need help with figuring out how to rotate on the Z axis only and face the other sprite. (The game is "top-down")
Thanks!
Answer by robertbu · Dec 05, 2013 at 07:31 PM
I'm having to guess a bit. I'm assuming the camera is at negative 'z' looking towards positive 'z'. I'm guessing that the up of the object is the side you want to face towards your target. If so, then this should work:
transform.up = target.position - transform.position;
If not this will work:
tranform.rotation = Quaternion.FromToRotation(transform.up, target.position - transform.position) * transform.rotation;
The problem is don't have any rotation code :S I tried your code, and it does like all the code i have already tried. It rotates on every axis except Z..
I'm not sure of your setup, and folks use 'axis' in different ways, and Unity may report a different rotation than the one you expect. As a first try, change the middle line to:
pos.x = transform.position.x;
or
pos.y = transform.position.y;
If that does not work, post a screen shot of your object with axes painted in and post the code you use for rotation (i.e. the code with the LookAt()). In addition, we need to know the natural orientation of your object (how it looks with rotation (0,0,0).
It still doesnt work. Here is a screenshot: http://imgur.com/6itYja3 And my code is just an object which has a GameObject called target (which it has to face)
I'm having to guess a bit. I'm assu$$anonymous$$g the camera is at negative 'z' looking towards positive 'z'. I'm guessing that the up of the object is the side you want to face towards your target. If so, then this should work:
transform.up = target.position - transform.position;
If not this will work:
tranform.rotation = Quaternion.FromToRotation(transform.up, target.position - transform.position) * transform.rotation;
Answer by Tomer-Barkan · Dec 05, 2013 at 10:02 PM
Just set transform.up
so that it points on your target (I'm assuming the sprite is facing upwards when it's not rotated)
public void LookAt2D(Transform target) {
transform.up = target.position = transform.position;
}
You can't use LookAt()
in 2D, because LookAt()
causes the transform's forward vector to face the target, but in 2D games your sprite faces up by default, not forward, so setting the forward vector to look at the target will do no good.
Your answer
Follow this Question
Related Questions
Sprite image not changing 0 Answers
Way to have 2D Sprites lit by Lights? 3 Answers
Distribute terrain in zones 3 Answers
Rotate a 2D sprite without rotating the transform 5 Answers
Strange artifacts in builds 0 Answers