- Home /
Raycast isnt working
I want to move the plaftomer in pong game when u drag the mouse in the collider. But it isnt working. Can u help me? 2p01 is name of object with collider and Player Transform is the platform.
private var ray : Ray;
private var rayCastHit : RaycastHit;
var Player : Transform;
function Update ()
{
if(Input.GetMouseButtonDown(0))
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, rayCastHit))
{
if(rayCastHit.transform.name == "2p01")
{
Move ();
}
}
}
}
function Move()
{
Player.transform.position.x = ray.point.x;
}
If "2p01" is the name of the gameObject, you should use:
if(rayCastHit.transform.gameObject.name == "2p01")
You should check what name is actually hit, or you write it out into a variable so you can see it in the inspector during the game, or you debug it.
Also, if the platform is a transform already, you should change the code in the $$anonymous$$ove() function to:
Player.position.x = ray.point.x;
Calling the transform of a transform is recursive!
Perhaps you want to change the type of Player to gameObject, because I think that your player is actually a gameObject in the scene isn't it?
If it is, and you change the type to gameObject, then you can leave the code in $$anonymous$$ove() as it is.
Answer by bompi88 · Nov 28, 2013 at 10:11 PM
You should be using the ray cast hit object to reference to the point where the hit took place.
function Move()
{
Player.transform.position.x = rayCastHit.point.x;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613123026im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Creating a working meshcollider in code 3 Answers
Flattening terrain under my object at start() 1 Answer
why are child colliders sometimes ignored? 2 Answers
Someone can help with Ray/Collide? 1 Answer