- Home /
How to fix a small raycast issue?
Hi there. I just started working with raycast
and now encountered an interesting problem.
I have this code snipet so that when a ray hits a collider the object that emitted the ray would move in a certain direction.You can find the snipet below.
This worked fine in my test scene.However when I put this in the actual script that is attached to my game object the ray is drawn above the game object,rather than coming from the game object it self.Which results in the raycast
completely missing it's target.
I tried using Vector3()
to position the ray in the correct position,but this didn't work as the ray seems to remain in the same position no matter what and not move with the object that is emitting it.
Just wondering is there something I am missing or is there something I could do so that the ray will always be drawn from the game object instead of above it?
All help is appreciated :D
var forward = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;
Debug.DrawRay(transform.position,-forward*15, Color.green);
if((Physics.Raycast(transform.position,-forward,hit,15))&&(onPlatform==true))
{
Debug.Log("Hit");
if(hit.collider.gameObject.tag == "MainPlatform")
{
MovePlatform();
}
}
If something is unclear ask away :D
Answer by clunk47 · Sep 05, 2013 at 04:01 PM
Just use -transform.forward and place your raycast statement in Update(). Also, no need for so many parentheses.
#pragma strict
var hit : RaycastHit;
var onPlatform : boolean;
function Update()
{
if(Physics.Raycast(transform.position, -transform.forward, hit, 15) && onPlatform)
{
Debug.Log("Hit");
if(hit.collider.gameObject.tag == "MainPlatform")
{
MovePlatform();
}
}
}
function MovePlatform()
{
//Code
}
That's great thank you. I had var forward = transform.TransformDirection(Vector3.forward); before the rest of the code and since that was removed it seems to work now. And I know there is no need but if I have to place more than once condition inside the
if()` then I prefer to use more parentheses to just separate out each once more clearly.
Answer by DDP · Sep 05, 2013 at 03:43 PM
What about this?
var forward = transform.TransformDirection(transform.forward);
Or just
var forward = transform.forward
But you don't even need to assign a variable, since you can just use
transform.forward
If you wanted to assign a variable and use TransformDirection, you'd use like:
var forward = transform.TransformDirection(Vector3.forward);
Your answer
![](https://koobas.hobune.stream/wayback/20220613113632im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
Gun Script Help 2 Answers
Trouble with raycasting 0 Answers
The name 'Raycast' does not denote a valid type ('not found') 1 Answer