Home > Blockchain >  How to prevent object from flying towards camera when using Ray-cast in unity?
How to prevent object from flying towards camera when using Ray-cast in unity?

Time:12-11

I got an unity project where object is meant to be moving with mouse cursor. The object moves fine, but when the object is still, it starts to float towards the camera that Ray-casts. I would like that the object doesn't float towards camera. Start Place A while later from the start

Here is the code I am using

I couldn't find any reason for objects behavior.

CodePudding user response:

What is happening here is when you send a ray and you get a hit result using hit.point it gives the exact location of the tris on the object it is hitting. Lets say the object is centered in the world (Vector3.zero). Ray is hitting a tris that is different than the position zero. Just because the object is in x:0y:0z:0 doesnt mean all the tris on the object is located at the same coordinates.

You get the coordinates of the hit.point, they are probably closer than the object center position, therefore the object is updating its center position to the hit.point location. And it does that every frame moving the object closer to camera.

You might want to try sending a ray from screen to world position. You can use custom vector length which would help to keep the object in the same depth you like.

Unity Docs Screen to World

CodePudding user response:

I'm quite a novice who's had issues with gameobjects following cursors myself. But could you try freezing the Y position in the Rigidbody and ensure gravity is unchecked?

More of a workaround if it even works.

Also I believe it's better practice to use rigidbody.position than transform.position. Try this:

public Rigidbody rigidbody;

void Update()
{
rigidbody.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, -Camera.main.transform.position.z));
}
  • Related