First time coder attempting to make a 2D Tower Defense game. The enemies spawn, but do not rotate. In the tutorial I am learning from (https://www.raywenderlich.com/107529/unity-tower-defense-tutorial-part-2) they mention child sprites being apart of this while providing you with the enemies. I wanted to do this from the ground up and so here we are! Considering I have no error codes… I can’t figure it out!
using UnityEngine;
using System.Collections;
public class MoveEnemy_A : MonoBehaviour {
[HideInInspector]
public GameObject[] waypoints_A;
private int currentWaypoint = 0;
private float lastWaypointSwitchTime;
public float speed = 1.0f;
void Start()
{
lastWaypointSwitchTime = Time.time;
}
void Update() {
transform.Translate (0, 0, Time.deltaTime * 1);
//1
Vector3 startPosition = waypoints_A [currentWaypoint].transform.position;
Vector3 endPosition = waypoints_A [currentWaypoint + 1].transform.position;
//2
float pathLength = Vector3.Distance (startPosition, endPosition);
float totalTimeForPath = pathLength / speed;
float currentTimeOnPath = Time.time - lastWaypointSwitchTime;
gameObject.transform.position = Vector3.Lerp (startPosition, endPosition, currentTimeOnPath / totalTimeForPath);
//3
if (gameObject.transform.position.Equals (endPosition)) {
if (currentWaypoint < waypoints_A.Length - 2) {
// 3.a
currentWaypoint++;
lastWaypointSwitchTime = Time.time;
RotateIntoMoveDirection();
} else {
//3.b
Destroy(gameObject);
//TODO: deduct health
}
}
}
// rotate enemies
private void RotateIntoMoveDirection() {
//1
Vector3 newStartPosition = waypoints_A [currentWaypoint].transform.position;
Vector3 newEndPosition = waypoints_A [currentWaypoint + 1].transform.position;
Vector3 newDirection = (newEndPosition - newStartPosition);
//2
float x = newDirection.x;
float y = newDirection.y;
float rotationAngle = Mathf.Atan2 (y, x) * 180 / Mathf.PI;
//3
GameObject sprite = (GameObject)
gameObject.transform.FindChild("Sprite").gameObject;
sprite.transform.rotation =
Quaternion.AngleAxis(rotationAngle, Vector3.forward);
}
}