- Home /
Casting ray forward from transform position
Hey everyone, I'm trying to cast a ray from my player object forward to see if a shot hits something. The problem is that I've only found a sample where the ray is casted from the camera's position. Here's the code:
void Update () {
if(Input.GetKey(KeyCode.Escape)){
Screen.showCursor = true;
}
if(Input.GetButtonDown("Fire1")){
Screen.showCursor = false;
Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
if(Physics.Raycast(ray, out hit)){
Debug.Log(hit.transform.name);
Debug.DrawLine(transform.position, hit.transform.position, Color.red);
}
}
}
But since I'm working on a top-down shooter, I would like to cast the ray from the players transform position (transform.x, transform.y, transform.z+1) into a forward direction. transform.z+1 is there because the ray should start at the gun's height. I hope some of you can help me with that.
Answer by strachpr01 · Aug 01, 2012 at 07:43 PM
ok try this one. first make an empty game object and position it where you want your gun then use this code. just reference the function when you want to perform the raycast. dont forget to set the raycast object in the inspector.
public GameObject raycastObject;
void CheckForHit(){
RaycastHit objectHit;
Vector3 fwd = raycastObject.transform.TransformDirection(Vector3.forward);
Debug.DrawRay(raycastObject.transform.position, fwd * 50, Color.green);
if (Physics.Raycast(raycastObject.transform.position, fwd, out objectHit, 50))
{
//do something if hit object ie
if(objectHit.name=="Enemy"){
Debug.Log("Close to enemy");
}
}
}
this code extends a raycast for 50m so depending on how far you wish it to go you may need to change these figures both on the debug and the actual raycast
also just make sure the raycast object is not inside the players collider or it will always register a hit of itself
Thanks mate, found this one to useful! Just edited it some:
private void SetTargetEnemy() {
RaycastHit objectHit;
// Shoot raycast
if (Physics.Raycast(transform.position, transform.forward, out objectHit, 50)) {
//Debug.Log("Raycast hitted to: " + objectHit.collider);
targetEnemy = objectHit.collider.gameObject;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613075025im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
raycast is pointing in two directions? 1 Answer
project a ray in a straight line 1 Answer
Fast object on collider not working 1 Answer
Trouble with Raycast shooting 1 Answer