- Home /
Make sprite look at vector2 in Unity 2D?
I'm working on a top-down 2D game but can't quite get a sprite to rotate towards any given vector. So far this is the best code I've got for it but the sprite will not look to the left side of the it, only the right:
transform.LookAt(WorldPos);
transform.rotation = new Quaternion(0,0,transform.rotation.z, transform.rotation.w);
WorldPos is the point I'm getting from ScreenToWorldPoint. I also have to force the rotation for x and y to 0 so that you can still see the sprite. Anybody got anything better for rotating a sprite toward an object in 2D? I'm thinking it should be this hard.
Answer by robertbu · Mar 03, 2014 at 04:25 AM
Here something better. I've posted it several times, but as usual searching for the answers is not turning up the ones I want:
var dir = WorldPos - transform.position;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
Note this code assumes that the 'forward' side of your sprite is the right side. If it is another side (like up), you will need to adjust the angle (subtract 90) before passing it to the AngleAxis() function;
Yup, works perfectly. I find it ridiculous this was so difficult for me. Thanks a ton.
thank you i thought with the 4.5 we would have lookAt for 2D already.
this problem was killing me for hours. thank you :_)
i had to add 180 to the angle to make it work. i wont pretend i know what all that atan degree math stuff does but thanks
Awesome, this works like a charm! I like the flexibility. I'm making a top down 2D game and some sprites I use have different directions. Here's my C# Util function for interested future viewers!
public enum FacingDirection {
UP = 270,
DOWN = 90,
LEFT = 180,
RIGHT = 0
}
public static Quaternion FaceObject(Vector2 startingPosition, Vector2 targetPosition, FacingDirection facing) {
Vector2 direction = targetPosition - startingPosition;
float angle = $$anonymous$$athf.Atan2(direction.y, direction.x) * $$anonymous$$athf.Rad2Deg;
angle -= (float)facing;
return Quaternion.AngleAxis(angle, Vector3.forward);
}
i used your C# code , it worked but it only facing the target not running into the target. how can i do that?
You might set the velocity of the Rigidbody2D component to a vector in the direction. If you wanted constant speed, the vector of the velocity would just be the direction normalized, multiplied by the speed.
I'd generally recommend against using the Atan2 function for working out angles on account of it's inefficiency. If you're making a 2D game, quaternions are usually more complicated than we need - I've made a class for handling 2D angles efficiently that has an implicit cast to Quaternion (so you can use it in any function etc. that requires a Quaternion), and if you're finding calculations with angles tricky, you may find it easier to use that. Angles Without Trigonometry (with Angle2D class download at bottom)
Amazing, I added this to my script, works like a charm!
Answer by feyyd · Jul 28, 2014 at 06:43 PM
I have enemy ships in a top down shooting game with very similar behavior. The following is a script that can be attached to a GameObject. It has a public variable for the target your are wanting your object to face, and the update behavior sets the rotation.
using UnityEngine;
using System.Collections;
public class FaceTarget : MonoBehaviour
{
public Transform target;
private Vector3 v_diff;
private float atan2;
void Update()
{
v_diff = (target.position - transform.position);
atan2 = Mathf.Atan2 ( v_diff.y, v_diff.x );
transform.rotation = Quaternion.Euler(0f, 0f, atan2 * Mathf.Rad2Deg );
}
}
You can programatically add this component and set its target variable as well. If your object is rotated already, you will have to add or subtract an offset from atan2 to compensate for the objects initial rotation.
works, but say i want to make this lookAt2D happen over time using Time.DeltaTime, where is this equition do i enter the Time.DeltaTime?
found it
float trackingSpeed
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0f, 0f, atan2 * $$anonymous$$athf.Rad2Deg ), trackingSpeed*Time.deltaTime);
Answer by IceTrooper · Sep 04, 2018 at 12:02 PM
There is a simpler and cleaner way to do this than in "Best answer":
Vector3 relativeTarget = (target.position - transform.position).normalized;
//Vector3.right if you have a sprite rotated in the right direction
Quaternion toQuaternion = Quaternion.FromToRotation(Vector3.right, relativeTarget);
transform.rotation = Quaternion.Slerp(transform.rotation, toQuaternion, rotationSpeed * Time.deltaTime);
Got my vote because of the Slerp implementation.
Had to change Vector3.right to Vector3.up. Works perfectly and as I need. Thanks!
Answer by Ferb · Oct 22, 2014 at 10:54 PM
There's a dph blog post explaining a few different ways to do the 2D LookAt. I think the simplest way is this:
transform.LookAt(Vector3.forward,Vector3.Cross(Vector3.forward,direction));
(where 'direction' is a vector pointing in whatever direction you want the sprite to face.)
This doesn't work for me. The sprite is still rotated along all 3 axes, making it look 3D. I would like the facing to be rotated only along the z axis.
Answer by Amyth17 · Aug 13, 2014 at 01:17 PM
Try this
using UnityEngine; using System.Collections;
public class JumpScript : MonoBehaviour {
public int playerSpeed = 5;
private float rotationx;
private float rotationy;
private Vector3 touchcoordinates;
private Transform myTrans;
private bool RestartButton_Bool;
public Transform background_map;
public Touch touch1;
public GameObject GameoverText;
void Start ()
{
//Caching of the variables
myTrans = this.transform;
}
// Update is called once per frame
void Update ()
{
//Keep the character without any rotation
myTrans.rotation = Quaternion.Euler(0,0,0);
//Check to see if the app is running over iOS or Android Devices
if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.Android)
{
//Get touch data
foreach (Touch touch in Input.touches)
{
touch1 = touch;
touchcoordinates = touch.position;
//Coverting touch coordinates in accordance with game use.
Ray ray = Camera.main.ScreenPointToRay(touchcoordinates);
transform.LookAt(ray.GetPoint(-1000),Vector3.forward);
}
touchcoordinates = touch1.position;
}
//Check if the app is ruuning anywhere other than Mobile devices
else
{
//Coverting touch coordinates in accordance with game use.
Ray ray1 = Camera.main.ScreenPointToRay(Input.mousePosition);
transform.LookAt(ray1.GetPoint(-1000),Vector3.forward);
}
//Moving the character forward
transform.Translate(Vector2.up * Time.deltaTime * 5);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613135231im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Finding the centre of two touches 2 Answers
Quaternion Rotate Towards Y Value 1 Answer
Sprite "face" second sprite only on Z axis 2 Answers
2D lock x,y rotation to look at target 2 Answers
Mirroring sprite around arbitrary axis causes collision issues 0 Answers