- Home /
Raycasts don't go the right direction unless i'm really far away (javascript)
I've got a very basic fps made, there are cubes that follow you around and lower your health if they touch you and you have a gun that you can kill them with (which i'm using raycast for) but I've run into a problem, my gun only works if I'm really far away from the cubes. if i get close at all, the ray doesn't go forward, which i can't figure out because I'm using transform.forward. This is the shoot function:
function Shoot () {
Debug.DrawRay(transform.position, CamScript.target, Color.red, 20, false);
var hit : RaycastHit;
if (canShoot == true) {
canShoot = false;
if (Physics.Raycast(transform.position, transform.forward, hit)) {
if (hit.transform.tag == "Enemy") {
hit.transform.SendMessage ("TakeDamage");
}
}
yield WaitForSeconds (10 / fireRate);
canShoot = true;
}
}
Your DrawRay and Raycast dont match. How can you be sure?
Create a variable of type Ray and set up what you want your ray to be in there. Use this for both the raycast and debug.
Can you explain how the drawray is wrong? not disagreeing just curious, CamScript.target is the point the gun points towards... sry for the late response, i have school but i should respond fast later in the day, trying wat u said now.
ya I can't figure out how to use the ray variable type... never done it like this before, when i try to do it like in the documentation it calls the ray variable "System.Type", but it should be something like "UnityEngine.Ray" right?
DrawRay draws rays, which have a position and a direction, like a raycast. You have two positions; that's not a ray.
ok that makes sense, i changed it to transform.forward and now it looks like the ray is going backwards, but only when i'm close to the cube
Answer by Inok · Jan 22, 2015 at 08:41 AM
Try instead "transform.forward" use "transform.TransformDirection(Vector3.forward)". Ray go backward when enemy close to you because start position of ray inside enemy's collider at that moment.
transform.forward is relative forward and is the same as transform.TransformDirection(Vector3.forward), except cleaner and easier to read.
Answer by team_eden · Jan 22, 2015 at 10:20 PM
then the position of your game object is reaching behind the cube? you need to set an anchor for your ray which is not part of your main object, as it apparently reaches farther away than the position of your actual intended object.
Put a blank object on the muzzle of your gun, called muzzleRayAnchor. Now, assuming your model is pointing forward if (Physics.Raycast(muzzleRayAnchor.transform.position, muzzleRayAnchor.transform.forward, hit))
It is important to set the forward of the muzzle Anchor, as it is the object that is staying in alignment with your gun, or what have you. Hope that helps
Your answer
Follow this Question
Related Questions
RaycastHit.distance 1 Answer
Why is this Coroutine not working ? 1 Answer
Raycast Distance Help 1 Answer