I am new to unity 3d game engine.I am creating a wood pattern puzzle game.I want to move small parts of wood according to the mouse position. I'm using the rigidbody2D. While moving I also want to detect collision from another wood parts and any other obstacle. Please help me out.
- 2Hi and welcome to SO. Please provide the code with what you've tried so far.Natalie Hedström– Natalie Hedström2015-11-25 06:46:06 +00:00Commented Nov 25, 2015 at 6:46
- What should happen if the player tries to move something into an other object?Samy Bencherif– Samy Bencherif2015-11-29 03:51:27 +00:00Commented Nov 29, 2015 at 3:51
1 Answer
You script would probably look something like this (it depends on the precise functionality you're looking for):
#pragma strict private var moveWithMouse : boolean = false; private var lastMousePosition : Vector3; function Update() { var changeInMousePosition : Vector3 = Vector3(0,0,0); if (lastMousePosition != null) { changeInMousePosition = Input.mousePosition-lastMousePosition; } lastMousePosition = Input.mousePosition; if (moveWithMouse) { transform.position += Camera.main.ScreenToWorldPoint(changeInMousePosition) - Camera.main.ScreenToWorldPoint(Vector3(0,0,0)); } } function OnMouseDown() { moveWithMouse = true; } function OnMouseUp() { moveWithMouse = false; } Here are all the documentation pages that explain the fancy parts of the code above.
- http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
- http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseUp.html
- http://docs.unity3d.com/ScriptReference/Input-mousePosition.html
- http://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
If there's anything in the code that's new to you and not covered in the documentation pages (such as Vector3, Transform, the Update function etc..) then you'd benefit from visiting a beginner's guide to unity before attempting a project.
In order to use my script, you must:
- Create a GameObject (the one you want to be draggable)
- Add a sprite renderer to it (and select the image you want for it)
- Add a 2d collider (polygon2d for precision, circle2d or box2d for speed)
- Create a new script and add it to the GameObject
Learning how to use Unity's editor might even be more essential than the programming itself when it comes to creating and customizing your own game, so if you don't know how to do the things above (create GameObject, and add Components) you should refer to a beginners guide to the Unity editor.
Here's a set of tutorial pages about Unity's editor: http://docs.unity3d.com/Manual/UnityBasics.html