- Home /
Trying to use transform.forward properly
I've been trying to use Transform.forward properly but I feel like I'm not using something properly with its interaction with raycast. The object moves forward when I rotate it, but it doesn't seem like raycast is detecting the object in front of my movement. Here is my code:
using UnityEngine;
using System.Collections;
public class Directional : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 fwd = transform.InverseTransformDirection(transform.forward);
if(Input.GetKeyDown(KeyCode.LeftArrow))
transform.Rotate(new Vector3(0, -10, 0));
if(Input.GetKeyDown(KeyCode.RightArrow))
transform.Rotate(new Vector3(0, 10, 0));
if(Input.GetKeyDown(KeyCode.UpArrow))
transform.Translate(fwd);
if (Physics.Raycast(transform.position, fwd, 200))
print("There is something in front of the object!");
}
}
Transform.forward is the same as Transform.TransformDirection(Vector3.forward). So since you are calling the inverse of transform direction on forward, you're just getting back Vector3.forward
Answer by robertbu · Feb 16, 2014 at 04:22 PM
Transform.Translate() (by default) is local coordinates. You can make it global coordinates by adding the Space.World. See the reference for Transform.Translate(). Physics.Raycast() uses world coordinates. For a transform, local forward will be 'Vector3.forward', and world forward will be 'transform.forward'. So for your code line 19 could be:
transform.Translate(Vector3.forward);
And line 21 could be:
if (Physics.Raycast(transform.position, transform.forward, 200))
And 'fwd' is no longer used.