- Home /
Question by
Sacrifice429 · Sep 26, 2017 at 10:17 PM ·
sprite2d rotationtower defense
2D Tower Defense Tutorial -- Sprite Rotation
No Error codes. I'm a noob. What am I doing wrong?
I'm sure there's a more basic approach. Appreciate the time!
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);
}
}
Comment
Answer by Animatick · Sep 26, 2017 at 10:55 PM
I would recommend using this tutorial, Quill18 does an amazing job at explaining things, and I have never had issues with any of this stuff.
Your answer
![](https://koobas.hobune.stream/wayback/20220612135715im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Rotate 2D tank head with two thumbs on IPhone 0 Answers
2D Sprite Rotation -- Help! 1 Answer
How to Rotate 2D Sprite Towards Moving Direction? 0 Answers
Sprite pivot and Transform gizmo at different positions 0 Answers
How Can I Change Sprite Max Size,Format and Compressor Quality in My Script 1 Answer