首页 文章

Unity - 跟随鼠标时捕捉到网格

提问于
浏览
2

试图创建一个类似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 回答

  • 2

    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;
        }
    

    因此,在根据鼠标位置获取值后,通过snap运行它,然后将结果应用于GameObject的变换位置 . 像这样:

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

    你可能不得不摆弄它,如果 Input.MousePosition 不能直接转换到你的坐标空间,以及快照距离(24来自我自己的用法,你的可能是1,5,10,50或100) .

相关问题