0
votes

Using unity 5.4, top down 2D game.

I have my tank enemy sprites with 4 different scripts. One to move and target my player, one to shoot, another to follow the player and last a damage handler script controlling the HP.The problem is when i play the game my sprites move diagonally or face the opposite way towards my player.(see screenshots). My sprites are fixed on the player the whole time.

enter image description here

enter image description here

The script that I have for following my player is

using UnityEngine;
using System.Collections;

public class FollowPlayer : MonoBehaviour {

public float rotSpeed = 90f;
Transform player;

void Update () {
    if(player == null)
    {
        GameObject go = GameObject.Find("Player");

        if(go != null)
        {
            player = go.transform;
        }
    }
    if (player == null)
        return;

    Vector3 dir = player.position - transform.position;
    dir.Normalize();

    float zAngle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;

     Quaternion desiredRot= Quaternion.Euler(zAngle, 0, 0);
     transform.rotation = Quaternion.RotateTowards(transform.rotation, desiredRot, rotSpeed * Time.deltaTime);

}}

I believe the issue with the movement of my sprite towards the player is the part of the code with

float zAngle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;

I do not believe I understand pretty much the whole meaning of the line. Or maybe its too complicated.

For further clarification. My tank sprites have to follow my player(at all times, till they come crushing on me), the turrets must be facing towards my player the whole time since they shoot at me. My bullets are fired towards the right direction but my sprites move correctly towards my player but face the other way.

1
i haven't read your question, but Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg means an angle in degrees equal to AoB. where A = x,0 and B = x,y and o = 0,0Bizhan
your problem is not really clear, do you want the enemy tank to look at you at all time ?Tengku Fathullah
So, that is the origin? Meaning it is where the point that is gonna follow my player is? Since i am using that float angle for the desiredRot.Ryoukami
Yes Tengku, my enemies are fixed on my player the whole time.Ryoukami
I can also give u the enemy movement script if you wanna try out yourselves.Ryoukami

1 Answers

0
votes

Different sprites may have different forward positions. Add a public float rotationFix = 90f; Then near the bottom: float zAngle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg + rotationfix; And use it to tweak the effective rotation and 'fix' the forward facing position of your sprite.

The tweaking can easily be done from the inspector during gameplay.