Unity-跟随鼠标捕捉到网格 [英] Unity - Snap to grid while following mouse

查看:116
本文介绍了Unity-跟随鼠标捕捉到网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试创建类似Connect 4的游戏.我使板模型的孔与网格对齐,因此我可以轻松地将圆放入其中.

Trying to create a Connect 4-like game. I made the board model have it's holes aligned with the grid so I can easily drop the circles into them.

问题是我不知道如何统一使对象跟随鼠标,同时捕捉到网格.

Problem is I don't know how to, in unity, make the object follow the mouse while also snapping to a grid.

代码:

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 before. I have these in my own math class (MathHelper). It snaps the values to multiples of another value (how far away each slot in your game is).

    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的变换位置.像这样:

So after getting the value based on the mouse position, run it through snap, then apply the result to your GameObject's transform position. Like so:

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

如果Input.MousePosition不能直接转换为坐标空间以及捕捉距离(您根据自己的使用使用24,则您可能是1、5、10、50),您可能不得不摆弄它.或100).

You might have to fiddle with it, if the Input.MousePosition isn't directly convertable to your coordinate space, as well as the snap distance (24 is from my own usage, yours might be 1, 5, 10, 50, or 100).

这篇关于Unity-跟随鼠标捕捉到网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆