0
\$\begingroup\$

I'm making this 2d collecting game in Unity where you collect fish. However I can't get them to face the direction they are going. I've asked on some Discords and got no answer. Thanks in advance.

Here's is the video of the fish.

And here's the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    public float minY;
    public float maxY;
    public float minX;
    public float maxX;
    public float speed;
    public float maxZ;
    Vector2 targetPosition;

    // Start is called before the first frame update
    void Start()
    {
        targetPosition = GetRandomPosition();
    }

    // Update is called once per frame
    void Update()
    {
        if ((Vector2)transform.position != targetPosition)
        {
            transform.right = (Vector2)targetPosition;
            transform.position = Vector2.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
            
        } else { 
            targetPosition = GetRandomPosition();
        }
    }
    
    Vector2 GetRandomPosition()
    {
      float randomX = Random.Range(minX, maxX);
      float randomY = Random.Range(minY, maxY);
      return new Vector2(randomX, randomY);
    }
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

It looks like you're trying to point your local right vector toward the target, but you're assigning a position instead of a direction.

transform.right = (Vector2)targetPosition;

First, get the direction from your current position to your target.

var targetDirection = targetPosition - transform.position;

Then you can either assign this directly as you were trying to do before...

transform.right = (Vector2)targetDirection;

Or you can construct the specific rotation you want, something like this:

var upToTarget = Quaternion.LookRotation(Vector3.forward, targetDirection);
var rightToUp = Quaternion.Euler(0, 0, 90);
var rightToTarget = upToTarget * rightToUp;

You can now assign this rotation to your transform:

transform.rotation = rightToTarget;

As mentioned in the comments, you can also flip the sprite when facing to the left, so the fish doesn't end up upside-down, with something like:

spriteRenderer.flipX = targetDirection.x < 0f;
\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .