### Unity - 跟随鼠标

``````using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LockToGrid : MonoBehaviour {
public float gridSize;
// Use this for initialization
void Start () {
}

// Update is called once per frame
void Update () {
SnapToGrid(gameObject);
}

void SnapToGrid(GameObject Object) {
var currentPos = Object.transform.position;
Object.transform.position = new Vector3(Mathf.Round(currentPos.x / gridSize) * gridSize,
currentPos.y,
currentPos.z);

}
}
``````

#### 1 个答案:

I've done this。我在自己的数学课（MathHelper）中有这些。它将值捕捉到另一个值的倍数（游戏中每个插槽的距离）。

``````    public static Vector3 snap(Vector3 pos, int v) {
float x = pos.x;
float y = pos.y;
float z = pos.z;
x = Mathf.FloorToInt(x / v) * v;
y = Mathf.FloorToInt(y / v) * v;
z = Mathf.FloorToInt(z / v) * v;
return new Vector3(x, y, z);
}

public static int snap(int pos, int v) {
float x = pos;
return Mathf.FloorToInt(x / v) * v;
}

public static float snap(float pos, float v) {
float x = pos;
return Mathf.FloorToInt(x / v) * v;
}
``````

`transform.position = MathHelper.snap(Input.MousePosition, 24);`