Unity - 跟随鼠标对齐网格
问题描述:
尝试创建Connect 4类游戏。我让电路板模型的孔与网格对齐,以便我可以轻松地将圆圈放入它们中。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);
}
}
答
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;
}
所以在获取基于鼠标位置的值后,通过捕捉运行它,然后将结果应用到您的GameObject的转换位置。像这样:
transform.position = MathHelper.snap(Input.MousePosition, 24);
您可能必须与它摆弄,如果Input.MousePosition
没有直接可转换到你的坐标空间,以及捕捉距离(24是从我自己的使用情况,您可能1,5,10,50或100)。
在行的上方添加一个不可见的目标,如果这是统一的5您可以在不可见的图像检查中使用以查看您的鼠标是否在目标上方,将检查块放在目标中 –