Hello, I have been following Brackey's how to build a tower defense game tutorial on youtube and have run into a problem with rotation. In the tutorial, he just uses a sphere as an enemy game object so he doesn't implement any rotation aspect to the movement of the game object. I used a free placeholder asset instead and thought it would be fun to try and figure out how to make it face the correct direction. As is the tutorial has you write the following code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour {
public float speed = 10f;
private Transform target;
private int wavepointIndex = 0;
void Start ()
{
target = Waypoints.points[0];
}
void Update ()
{
Vector3 dir = target.position - transform.position;
transform.Translate( dir.normalized * speed * Time.deltaTime, Space.World );
if (Vector3.Distance(transform.position, target.position) <= 0.4f)
{
GetNextWaypoint();
}
}
void GetNextWaypoint()
{
if (wavepointIndex >= Waypoints.points.Length - 1)
{
Destroy(gameObject);
return;
}
wavepointIndex++;
target = Waypoints.points[wavepointIndex];
}
}
I've worked on a few tutorials so far and have little understanding of how most of this works, but I thought I might have luck looking at bits of code from the other tutorials that involve rotation and copying aspects over that might help me achieve that in this game. So far I've tried a bunch of things that don't work but the closest I've gotten involved adding the following segment into void update:
Quaternion targetRotation = Quaternion.LookRotation(dir);
this.transform.rotation = Quaternion.Lerp(this.transform.rotation, targetRotation, Time.deltaTime * 5);
The only issue there is that though the enemy appears to rotate as it is supposed to when heading from waypoint to waypoint, its initial correct orientation is lost and the frog faces the wrong direction and moves with its back going forward. My apologies for the prolonged explanation, basically I'm wondering if this is at all the correct course of action for achieving what I desire and how to fix it. Thank you for time.
↧