Hi there, I have a basic script that simply makes a game object move towards an empty game object. The only problem is that I only want it to move towards it on the x and z axis. I tried making a ne vector with the x and z values of the empty game object and the y value of the character game object but for some reason it still points to the y axis. I’ll past snippets of my code and also the whole lot hopefully one of you can help. I thought maybe a vector 2 would do the trick but that actually takes the x and y positions not x and z which is what I need.
// this would be the new vector of the combined transform positions
Vector3 dirxz = new Vector3( path[currentPoint].position.x, transform.position.y, path[currentPoint].position.z);
// this is the movement part of the script only instead of the second value being path[currentPoint].position I would add the new vector I made
if (Quaternion.Angle(transform.rotation, targetRotaion) <= 0.1f && move)
{
// turned = true;
transform.position = Vector3.MoveTowards(transform.position, path[currentPoint].position, Time.deltaTime * speed);
}
here’s the full code ignore the fact that it’s all over the place I’ll tidy it all up when I’m done.
public class R2D2_logic : MonoBehaviour {
public Transform[] path;
public float speed = 5.0f;
public float rotspeed = 0.1f;
public float reachDist = 1.0f;
public int currentPoint = 0;
public float rotation;
public int complete = 0;
public bool turned = false;
public bool move = true;
public AudioClip R2D2;
Quaternion targetRotaion;
private void Start()
{
//var R2D2: audio
}
// Update is called once per frame
void Update () {
float dist = Vector3.Distance(path[currentPoint].position, transform.position); // get distance between refernce and current pos
//Debug.Log ("distance " + dist);
Vector3 dir = path[currentPoint].position - transform.position; // get target vector for pointing dirrection
//Vector3 dirxz = new Vector3( path[currentPoint].position.x, transform.position.y, path[currentPoint].position.z);
targetRotaion = Quaternion.LookRotation(dir); // gets quanterian vector dir
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotaion, Time.deltaTime * rotspeed); // turns R2D2 in dirrection of next point
if (Quaternion.Angle(transform.rotation, targetRotaion) <= 0.1f && move)
{
// turned = true;
transform.position = Vector3.MoveTowards(transform.position, path[currentPoint].position, Time.deltaTime * speed);
}
if (dist <= reachDist)
{
currentPoint++;
AudioSource.PlayClipAtPoint(R2D2, transform.position, 1f);
// Debug.Log("position" + currentPoint);
}
if (currentPoint >= path.Length)
{
currentPoint = 0;
//Debug.Log("position" + currentPoint);
}
}
void R2D2Events()
{
move = false;
}
void OnDrawGizmos()
{
if (path.Length > 0) {
for (int i = 0; i < path.Length; i++)
{
if (path[i] != null)
{
Gizmos.DrawSphere(path[i].position, reachDist);
}
}
}
}
}