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.
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.
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,0 – Bizhan