- Home /
Can someone explain to me why this raycast doesn't fire straight?
using UnityEngine;
using System.Collections;
public class Firegun : MonoBehaviour {
public float shots=1.0f;
public float spread=5.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
RaycastHit target;
Vector3 targetDir = new Vector3 (transform.Find ("Main Camera").transform.rotation.x * -1,transform.rotation.y *-1,transform.rotation.z);
//print ("Vector3: ("+targetDir.x+","+targetDir.y+","+targetDir.z+"), Direct: ("+transform.Find("Main Camera").transform.rotation.x+","+transform.rotation.y+","+transform.rotation.z+")");
if (Input.GetMouseButtonDown (0)){
print ("Clicked!");
for (float i=0;i<=shots;i++){
if (Physics.Raycast (transform.position,targetDir,out target,1000.0f,1)){
print (target.collider.gameObject.name+" was hit in the direction of ("+targetDir.x+","+targetDir.y+","+targetDir.z+") at a distance of "+target.distance+"!");
Debug.DrawRay (transform.position,targetDir,Color.green,5,true);
Debug.DrawLine (transform.position,target.point,Color.red,15,true);
}
}
}
}
}
I don't really understand why this doesn't work. The X axis is where the camera pivots and the Y axis is where the player pivots. It's supposed to fire straight (I'm going to add spread once it does). It seems to fire off to the side or to the ground depending on where I'm looking but never straight.
Answer by Jeff-Kesselman · Jun 20, 2014 at 02:52 AM
trasform.rotation is not a vector. Its a quaternion.
Try using one of the transform direction vectors like transform.forward instead.
Remember quaternions have x, y, z and w. You really don't want to access these values directly unless you have a PhD in mathematics.
If you want to know the vector direction of a Quaternion then you take the 0 degree unit vector, set a trasform to the quaternion, and transform the vector
But for your uses I suspect the already existing transform direction vectors (forward, right, up) are al you need.
$$anonymous$$aking this suggestion specific, change line 15 to:
Vector3 targetDir = Camera.main.transform.forward;