HI So I am trying to do a script, that make a 3d object (rocket) follow the cursor mouse. For instance if i put the mouse on the left upper corner of my gameplay, so the rocket will go there too. So i am looking for a script (or a piece of it) that can make an object foolw the cursor. Thank you.
As per our initial observation we found some workaround for the issue given below:- 1. To move the 3d object with mouse position we have to first convert the mouse position into the 3d space position. 2. “ScreenToWorldPoint” is the predefined method that converts position to the world space position. 3. For better movement of a 3d object we are using “rigidbody.position” instead of “transform.position” because of its physics values. 4. You can also use DoTween for smooth transition alternatively. Please have a look on below code snippet:- public Rigidbody rigidbody; void Update() { rigidbody.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, -Camera.main.transform.position.z)); }
It works, but can you please epxlain this line? without it follow doesnt work as accurate so if you can mathematically explain it as i'm learning math as well. Thanks [-Camera.main.transform.position.z]
ScreenToWorldPoint() needs the depth relative to the camera to return an accurate result. You should generally be using Camera.main.nearClipPlane as the z component of your calculation.
I know its been a while since this question was answered, but i tried this and i ran into a problem. Whenever i am moving an object, i can move it trough other objects, like there was no collisions, but once i just drop it, it collides normaly. Is there a way to fix this? I have the same code, only my Z coordinate is hardcoded to 10f. Thanks.
New problem, new post please. When you post, here is how to report your problem productively in the Unity3D forums: http://plbm.com/?p=220 This is the bare minimum of information to report: - what you want - what you tried - what you expected to happen - what actually happened, especially any errors you see - links to documentation you used to cross-check your work (CRITICAL!!!) If you post a code snippet, ALWAYS USE CODE TAGS: How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/ With Physics (or Physics2D), never manipulate the Transform directly. If you manipulate the Transform directly, you are bypassing the physics system and you can reasonably expect glitching and missed collisions and other physics mayhem. Always use the .MovePosition() and .MoveRotation() methods on the Rigidbody (or Rigidbody2D) instance in order to move or rotate things. Doing this keeps the physics system informed about what is going on. https://forum.unity.com/threads/col...-unity-physic-rigidbody.1216875/#post-7763061 https://forum.unity.com/threads/oncollisionenter2d-not-being-called.1266563/#post-8044121