- Home /
Object following mouse problem
I have code that makes an object spawn at mouse position when I hit a button. The object is suppose to follow the mouse until I click. The code works perfectly except for the object gets closer and closer to the camera until it passes it then it goes back to the hit point of the ray cast and repeats. What do I have wrong?
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit : RaycastHit;
if(buildingNumber == 1)
{
if(inBuildingProcess == false)
{
if(Physics.Raycast(ray,hit,10000) == true)
{
inBuildingProcess = true;
structure = Instantiate(buildingOne.building, hit.point, Quaternion.identity);
}
}
if(Physics.Raycast(ray,hit,10000) == true)
{
structure.transform.position = hit.point;
}
if(Input.GetMouseButtonDown(0) == true)
{
print("build again");
inBuildingProcess = false;
}
Answer by BigRoy · Jan 04, 2014 at 07:59 PM
It's likely that the hit.point is always the front of the surface (the actual point being hit) instead of the pivot point / position the object is actually at.
Therefore it slightly moves towards the camera on each raycast by the amount the surface point that is hit is away from the object's pivot. :) Does that make sense?
The above wasn't the solution for the topic starter. Yet his exact problem/solution is in the comment on this answer:
No that's not it. But you lead me to what is. The ray cast spawns the object where it hits. Then it cast again and hits the object moving it because it hit a closer spot. And repeats until the object is off screen. Then moves it to the ground again.
No that's not it. But you lead me to what is. The ray cast spawns the object where it hits. Then it cast again and hits the object moving it because it hit a closer spot. And repeats until the object is off screen. Then moves it to the ground again.
I added your comment into the answer so now it should be correct with the question/problem. :)
Your answer

Follow this Question
Related Questions
RaycastAll - get entry and exit points? 3 Answers
Clicking on an Object to Make it the Variable Target 1 Answer
Setting Scroll View Width GUILayout 1 Answer
Raycast Pause Between Hits? 0 Answers
Raycast.hitpoint always returning back to the camera 0 Answers