0
votes

Needed help here, I've been following this tutorial about Enemy Patrolling, https://www.youtube.com/watch?v=KKU3ejp0Alg

The tutorial tell us to set 2 Empty Game Objects and the coordinates so the sprite will walk from one direction to another, the walking does working, however the rotation of the sprite became really weird, the 'Worm' sprite is suppose to move left and right now it change into facing upward Please look at this image,

When moving from left to right enter image description here

When moving from right to left

enter image description here

public Transform[] patrolPoints;
public float speed;
Transform currentPatrolPoint;
int currentPatrolIndex;

// Use this for initialization
void Start()
{
    currentPatrolIndex = 0;
    currentPatrolPoint = patrolPoints[currentPatrolIndex];
}

// Update is called once per frame
void Update()
{
    transform.Translate(Vector3.up * Time.deltaTime * speed);

    if (Vector3.Distance(transform.position, currentPatrolPoint.position) < .1f) {
        if (currentPatrolIndex + 1 < patrolPoints.Length)
            currentPatrolIndex++;
        else
            currentPatrolIndex = 0;
        currentPatrolPoint = patrolPoints[currentPatrolIndex];
    }

    Vector3 patrolPointDir = currentPatrolPoint.position - transform.position;
    float angle = Mathf.Atan2(patrolPointDir.y, patrolPointDir.x) * Mathf.Rad2Deg - 90f;

    Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
    transform.rotation = Quaternion.RotateTowards(transform.rotation, q, 180f);

}

This is the code

Thank you

2
Instead of rotate, set the local scale x value to -1 or minus what ever the positive is. Surprisingly this works. - Catwood
@Catwood How to do that? change which code? Thanks - Carmen C
swap the last 2 lines for transform.localScale = new Vector2(-1,1); to flip it. - Catwood

2 Answers

2
votes

You can pass the optional parameter Space.World to your translation to move your object relative to world space instead of object space. That should prevent your object from rotating.

transform.Translate(Vector3.up * Time.deltaTime * speed, Space.World);

You can read more about it in the documentation.

0
votes

You probably rotated the enemy sprite by 90 degrees. Try placing all your scripts into empty game object with no rotation, than place the enemy sprite as child of the empty game object and rotate as you need. This way your logic won't collide with your graphics.