
物體拖拽,碰到墻就不能繼續向墻外拖了。
拖拽已經寫好了,
using System.Collections;
using UnityEngine;
public class Tuozhuai : MonoBehaviour
{
//目標物體的螢屏空間坐標
Vector3 targetScreenLocation;
//目標物體的世界空間坐標
Vector3 targetWorldLocation;
//目標物體的空間變換組件
Transform transform1;
//滑鼠的螢屏空間坐標
Vector3 mouseLocation;
//偏移
Vector3 offset;
//視角移動,
private Camera camera1;
//
public static Tuozhuai _instance;
void Start()
{
camera1 = GameObject.Find("fushi").GetComponent<Camera>();
}
void Update()
{
}
void Awake()
{
transform1 = transform;
_instance = this;
}
void OnCollisionEnter(Collision collisionInfo)
{
Debug.Log("碰撞到的物體的名字是:" + collisionInfo.gameObject.name);
}
IEnumerator OnMouseDown()
{
print(transform.position);
//把目標物體的世界空間坐標轉換到他自身的螢屏空間坐標
targetScreenLocation = camera1.WorldToScreenPoint(transform.position);
print(targetScreenLocation);
//儲存滑鼠的螢屏空間坐標(Z值使用目標的螢屏空間坐標)
mouseLocation = new Vector3(Input.mousePosition.x, Input.mousePosition.y, targetScreenLocation.z);
//計算目標物體與滑鼠物體在世界空間中的而偏移量
offset = transform.position - camera1.ScreenToWorldPoint(mouseLocation);
//滑鼠左鍵按下
while (Input.GetMouseButton(0))
{
//儲存滑鼠的螢屏空間坐標(Z值使用目標物體的螢屏空間坐標)
mouseLocation = new Vector3(Input.mousePosition.x, Input.mousePosition.y, targetScreenLocation.z);
//把滑鼠螢屏坐標轉化為世界坐標
targetWorldLocation = camera1.ScreenToWorldPoint(mouseLocation) + offset;
transform1.position = targetWorldLocation;
//更新目標物體的世界空間坐標
//等待固定更新
yield return new WaitForFixedUpdate();
}
}
}
uj5u.com熱心網友回復:
我沒想到很好的辦法處理這個問題,也沒能找到很好的辦法。我的做法是這樣的,當發生碰撞的時候,記下拖動物件的位置,只要處于接觸狀態就回到碰撞時的位置。
void OnCollisionEnter(Collision collision){
touch_position = transform.position;
}
void OnCollisionStay(Collision collisionInfo) {
transform.position = touch_position;
}
這樣做勉強能實作樓主的要求,但是,1,周圍的物體必須固定,不然會被撞走,2,拖動很快的時候,會發生穿越的bug。
uj5u.com熱心網友回復:
怕穿墻 移動物體的時候 加射線連線判斷是否穿了 如果是 拉到第一個碰撞點就是了
uj5u.com熱心網友回復:
學習一下,應該是正解!轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/72648.html
標籤:Unity3D
上一篇:如何屏蔽螢屏下滑拖出系統下拉選單
