Well, I’m working on a FPS. I have a gun and want it to fire but not using prefabs, I want it to shoot with Raycast. I started coding it but it doesn’t seem to work. I can’t find my mistake, please help! I want the gun to move up every time the ray hits a collider with the tag “jump”. I want the ray to go from the center of the screen straight forward. Here’s my code:
void Update{
Ray ray = Camera.main.ScreenPointToRay(transform.position);
RaycastHit hit = new RaycastHit();
if (Physics.Raycast(ray, out hit)){
if (hit.collider.gameObject.tag =="jump"){
transform.Translate(Vector3.up);
}
}
}
}
So basically this casts a ray, it checks the collider’s tag, if the tag is “jump” it moves the object towards Vector3.up Any idea why this doesn’t work? Thanks!
You’re constructing your ray incorrectly. A camera’s ScreenPointToRay method takes in a Vector3 with it’s X and Y components describing the point on the screen that you want the ray to go through (the Z component is ignored). Like fire7side suggests, you can use the current mousePosition (as it tells you the mouse’s position in terms of screen pixel position) if your mousePosition is at the center of the screen. A better way to always get a ray going through the center would be to use ViewportPointToRay passing in a constant of new Vector3(0.5f,0.5f, 0.0f) as it accepts normalized coordinates instead.
But I think the most efficient way of constructing your ray would be to use the camera’s transform directly:
var cameraTransform = Camera.main.transform;
var ray = new Ray(cameraTransform.position, cameraTransform.forward);
I’m not too clear on what you want to happen next: You want to move the gun or the object (you say one then the other)? Your script is currently translating the parent GameObject that it’s attached to 1 unit in the world’s “up” direction (Y-Axis). If you want to simulate recoil on the gun (but only when it hits an object tagged “jump” for some reason specific to your project) then you might want to rotate the view along it’s X-axis by some amount. If you want to move the object that it hits then you need to modify the position of the gameObject referenced in your RaycastHit result. Or add a force to its Rigidbody component if it has one, as simply translating it will “teleport” it from one frame to the next.
Finally, I’m assuming your code is just an example of what you’re doing as having this running on Update the way its currently written will execute every frame, regardless of whether the gun is shooting or not.
Thank you both! Yes Roland, that did really help. The idea is that the gun object simulates recoil only if the ray hits an object with the tag “jump”. Of course, it is just an example, as I have another condition: