- 拖拽刚体的时候会出现穿墙乱飞的现象(以下用的是2D刚体,3D刚体也同理),这是因为刚体的移动还会触发物理碰撞的机制,强制改变坐标会出现问题,unity里自带了让刚体以符合物理规律运动的方法MovePosition
- 给2d物体添加2d的碰撞体和刚体,给待碰撞物体添加碰撞体,注意,主物体的Rigidbody2D-Collision Detection设置为Continuous(实时监测物体碰撞),更加真是还原碰撞场景,新建脚本直接挂载到主物体上,上代码
using UnityEngine;
public class Move : MonoBehaviour
{
Rigidbody2D rigidbody2d;
bool bar = false;
void Start()
{
rigidbody2d = GetComponent<Rigidbody2D>();
}
public void OnMouseDown()
{
bar = true;
}
public void OnMouseUp()
{
bar = false;
}
public void OnMouseDrag()
{
if (bar)
{
Vector3 mousePositionScreen = Input.mousePosition;
Vector2 mousePosition2D = new Vector2(mousePositionScreen.x, mousePositionScreen.y);
Debug.Log("Mouse Position (Vector2): " + mousePosition2D);
rigidbody2d.MovePosition(Vector2.Lerp(rigidbody2d.position, mousePosition2D, Time.deltaTime * 100f));
}
}
}
- 场景中物体借助了Event Trigger组件实现,具体设置如下
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d9f735a7c9b1c24981cb56159a8b6560.png#pic_center)