- Home /
Raycasting help
Hi, im new to Unity 3d and just completed the VTC Getting started with Unity 3d tutorial set. I completed everything fine.
I now have a turret that can kill me, grenades and explosions etc.
Now im trying to create a script that will allow me to kill the turret with my grenades
Im using a raycast to check for collisions, and checking if any of the objects i hit are tagged "Turret", then i want to print it to the console screen so i know that my raycasts work before i make the turret lose health.
The problem is my raycasts are not working.
Here is my code
var target: Transform;
function update() { var hit : RaycastHit;
if(Physics.Raycast(transform.position, target.position))
{
if(hit.collider.gameObject.tag == "Turret")
{
print("hitting");
}
}
}
What is wrong
I have attached this script to my player, and the "target" is set to the turret.
Help would be greatfully apreciated.
Thanx :D
Answer by opsive · Aug 11, 2010 at 05:52 AM
Based on your input parameters, you should be doing a linecast instead of a raycast:
http://unity3d.com/support/documentation/ScriptReference/Physics.Linecast.html
Answer by Cyb3rManiak · Aug 11, 2010 at 03:02 PM
Or alternatively...
The method is defined as:
static function Raycast (origin : Vector3, direction : Vector3, distance : float = Mathf.Infinity, layerMask : int = kDefaultRaycastLayers) : bool
The second parameter is direction, not the destination position.
So try:
function update() { var hit : RaycastHit;
if(Physics.Raycast(transform.position, target.position - transform.position))
{
if(hit.collider.gameObject.tag == "Turret")
{
print("hitting");
}
}
}
Also, Debug.DrawRay is your friend in these cases. Visualizing the ray/line is very helpful.
Your answer
Follow this Question
Related Questions
Raycasting will not hit some imported meshes with mesh colliders? 2 Answers
Raycast problem 1 Answer
RaycastHit if/else Problem (bug?) 0 Answers