- Home /
transform.forward using global forward instead of local
Hi, I am making an AI spider which will stop when it gets too close to a wall. However, using my code below it only succeeds in executing Idle()
when facing the northern wall of the maze (Global forward).
Here is my code:
using UnityEngine;
using System.Collections;
public class Spider : MonoBehaviour {
public float movementSpeed, rotationSpeed;
//Called by game manager after instantiation
public void SetLocation (MazeCell cell) {
transform.localPosition =
new Vector3(
cell.transform.localPosition.x,
5f,
cell.transform.localPosition.z
);
float startingRotation = Mathf.RoundToInt(Random.Range(-0.5f,3.49999f));
transform.rotation = Quaternion.Euler(0,startingRotation * 90,0);
}
void Update() {
if (Physics.Raycast(transform.position, Vector3.down, 0.5f)) {
if (!Physics.Raycast(transform.position, transform.forward, 2)) {
Walk();
} else {
Idle ();
}
}
}
private void Idle() {
animation.Play("idle");
}
private void Walk() {
transform.Translate(transform.forward * movementSpeed * Time.deltaTime);
animation.Play("walk");
}
}
Have you tried checking in Scene View if the blue axis on the Gizmo is pointing in the right direction (local forward). There might be something going on with your local rotations.
@sevensixtytwo Upon selecting the spider (from its starting rotation) the blue arrow is facing the correct way (to its face). As I rotate the spider (in the inspector) the blue arrow stays the same. Is this correct?
Would it be you are misusing transform.forward and Vector3.forward. One is the object forward which follows its rotation, the other is the world forward which is a constant always pointing the same direction (blue arrow in the corner gizmo).
Yes @fafase I have researched these and the one I have used (`transform.forward`) is definitely the one for local space (unless used with a capital 't').
Your answer
Follow this Question
Related Questions
How edit transform.forward value ? 0 Answers
Unity Rotate Raycast on Quaternion 1 Answer