猴子都会用的unity自动吸附 复制即用

滑动选择ui的项目经常要用到自动吸附并且放大显示。这个方法可以实现

首先,创建一个2D物体。添加碰撞器和刚体

把刚体的重力取消,打开碰撞器的触发器

添加这个脚本

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

public class triger : MonoBehaviour
{
    public int Stop;//碰到之后停顿一会儿。不要也可以
    private void FixedUpdate()
    {
        if (Stop == 0)
            GetComponent().position += new Vector3(Input.mousePosition.x / 10000, 0, 0);//跟随鼠标自动移动
        else Stop--;
    }
    private void OnTriggerEnter(Collider other)
    {

        GetComponent().localScale = new Vector3(2f,2f,2f);//放大
        Debug.Log("Hello"+other.name);//报告碰到的物体名字
        GetComponent().position = other.transform.position;//吸附
        Stop = 5;//碰到之后停顿
    }
    private void OnTriggerExit()
    {
        GetComponent().localScale = new Vector3(1f, 1f, 1f);//离开后缩小
    }

}

再创建一个物体,作为吸附物。让挂了上面那个脚本的物体碰到他之后就被吸附并执行方法

同样。这个吸附物也要有碰撞器和刚体(碰撞器不需要触发器)

你可能感兴趣的:(UNITY学习之路,猴子系列,unity,ui,游戏引擎)