To make a small Indie Game like classic unblock game or something similar, the first function we should implete in Unity is to enable users using mouse to ‘drag’ different objects in its specific direction(x-coordinate / y-coordinate).
Classic unblock game:
|
|
GetMouseButtonDown()
The parameter 0 in function GetMouseButtonDown(0) means user pressed the left click, and it returns bool value.
Button:
0 : the left click of mouse
1 : the right click of mouse
2 : the middle click of mouse
Camera.main.ScreenPointToRay()
1. The Camera.main means the main camera (camera which is tagged ‘main’)in current scene.
2. ScreenPointToRay:
public Ray ScreenpointToRay(Vector3 position);
Definition: Returns a ray going from camera through a screen point. Resulting ray is in world space.
Screenspace: Defined in pixels. The bottom-left of the screen is (0,0); the right-top is (pixelWidth,pixelHeight)/(Screen.width, Screen.height).
3. mousePosition:
public static Vector3 mousePosition;
Definition: The current mouse position in pixel coordinates.
Note: Position values < 0 or > (Screen.width,Screen.height) indicate that the mouse cursor is outside of the game window.
Physics.Raycast()
This function has a lot of expression ways. It returns bool True when the ray intersects any collider.
out RaycastHit can store information back from a raycast.
float maxDistance can set your reachable area of a raycast.
int layerMask can selectively ignore Colliders when casting a ray.
QueryTriggerInteraction queryTriggerInteraction allows you to control whether or not Trigger colliders generate a hit, or whether to use the global Physics.queriesHitTriggers setting.
|
|
Click and drag object at full speed
The idea used here is very simple. offset records the orignial distance between ScreenToWorldPoint and selected object’s transform. If user moves mouse on screen, the new ScreenToWorldPoint should be add to offset to get the new position of selected object.
Notice that we use bool value drag and function GetMouseButtonUp(0) here to make sure not happen the situation where next time user clicks without selecting object but the value drag and selected_object exist and then make an error.
Reference: Unity Community-Answer
Note: For most moving Game Object if we want to change the position of it, we usually use Rigidbody.position(Vector 3) instead of Transform.Translate(Vector 3)
Reference: transform.Translate vs rigidbody.MovePosition?
|
|
Change the moving direction
The idea to make sure objects are moved in its specific direction(x/y), is that, add tag to different objects, like ‘Vertical’ or ‘Horizontal’. Then use a if function to make sure which way to move it, and then change the moving function a little bit.
|
|
近期评论