Home > Net >  turning towards an object in Unity
turning towards an object in Unity

Time:02-01

Good times. How do I implement the NPC rotation towards the selected object?

public GameObject BufferObject;
public float MoveSpeed = 1f;
void Update()
{
    float step = MoveSpeed * Time.deltaTime;
    transform.position = Vector2.MoveTowards(transform.position, BufferObject.transform.position, step);
}

Here is the script for moving the NPC to the selected object (Buffer Object) and the movement works perfectly, but the implementation of the rotation causes Me difficulties, please advise. For Unity2D.

CodePudding user response:

Simply get the desired direction

var direction = (BufferObject.transform.position - transform.position).normalized;

and then the desired rotation using Quaternion.LookRotation like e.g.

var targetRotation = Quaternion.LookDirection(direction);

Then either apply it directly if you want it immediately

transform.rotation = targetRotation;

Or if you want it smooth you could use e.g. Quaternion.RotateTowards like

transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, anglePerSecond * Time.deltatime);

Have in mind though that it might look awkward if the rotation is too slow since your NPC could move back/sidewards already while still not fully looking towards the target ;)

So you might want to wait until

if(Quaternion.Angle(targetRotation, transform.rotation) <= certainThreshold)
{
    ... your movement code
}

CodePudding user response:

So the answer and the solution from Me, albeit stupid, but working. In order to reflect the sprite, you need to get a variable, either 1 or -1 (For Scale). This code will show the distance from one NPC to the object:

BufferObject.transform.position.x - transform.position.x

And here I get a lot of values as if to the left of the NPC, then -x... , and if to the right, then x... thereby it is possible to determine which side of the object, so also level the value from here (Optional) to 1 or -1 and apply this result to transform.localScale and thereby solve the problem of how to reflect (Rotate the sprite) towards the object. Use it for your health :) Complete code:

    float localPositionAmount = BufferObject.transform.position.x - transform.position.x;

    if (localPositionAmount >= 1)
    {
        gameObject.transform.localScale = new Vector3(1, transform.localScale.y, transform.localScale.z);
    }
    if (localPositionAmount <= -1)
    {
        gameObject.transform.localScale = new Vector3(-1, transform.localScale.y, transform.localScale.z);
    }
    if (localPositionAmount == 0)
    {
        gameObject.transform.localScale = new Vector3(transform.localScale.x, transform.localScale.y, transform.localScale.z);
    }

Yes, the code is the simplest and without enumerations and other things, but it works perfectly. I still had to figure it out myself...

  •  Tags:  
  • Related