试图创建一个类似Connect 4的游戏 . 我让板模型的孔与网格对齐,这样我就可以轻松地将圆圈放入其中 .
问题是我不知道如何在统一中使对象跟随鼠标同时也捕捉到网格 .
码:
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)中有这些 . 它将值捕捉到另一个值的倍数(游戏中每个插槽的距离) .
因此,在根据鼠标位置获取值后,通过snap运行它,然后将结果应用于GameObject的变换位置 . 像这样:
transform.position = MathHelper.snap(Input.MousePosition, 24);
你可能不得不摆弄它,如果
Input.MousePosition
不能直接转换到你的坐标空间,以及快照距离(24来自我自己的用法,你的可能是1,5,10,50或100) .