- Home /
2D LookAt not working as intended
So I have looked this up and found http://www.dphsw.co.uk/blog/?p=172, but when I try it out, it did not work for me so I had to add a line so that the sprite would be visible. There is still a problem with it, here is an image of the problem. What am I doing wrong?
using UnityEngine;
using System.Collections;
public class Target : MonoBehaviour
{
private Transform target;
private RaycastHit2D hit;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if (!target)
{
hit = Physics2D.Raycast(transform.position, Vector2.up);
Debug.DrawRay(transform.position, Vector2.up);
}
if (target)
{
hit = Physics2D.Raycast(transform.position, target.position - transform.position);
Debug.DrawRay(transform.position, target.position - transform.position);
var direction = target.position - transform.position;
transform.LookAt(Vector3.forward, direction); //target has to be 0,0,1 in order for it to be visible.
transform.rotation = new Quaternion(0, 0, transform.rotation.z, transform.rotation.w);
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Enemy" && !target)
{
target = other.gameObject.transform;
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject.transform == target)
{
target = null;
}
}
}
Answer by robertbu · Nov 17, 2014 at 09:24 PM
The best thing for a sprite is to make the texture so that the front is on the right. Then you can do this:
if (target)
{
hit = Physics2D.Raycast(transform.position, target.position - transform.position);
Debug.DrawRay(transform.position, target.position - transform.position);
Vector3 direction = target.position - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
So using Atan2 is okay? I am planning on having like 500 of these things on the screen, would performance be okay using Atan2?
There are other ways to solve this rotation, but I doubt they are any more efficient than this one. I doubt that Atan2() will play any role in performance issues you have with 500 objects.
Your answer
Follow this Question
Related Questions
LookAt() not working with mouse as target in 2D 1 Answer
2D Sprite Rotation 0 Answers
Joystick 2D Sprite Rotation and Movement 0 Answers
2D Sprite Animation - Rotate animation on axis 1 Answer
2D rotation question 0 Answers