[英]Move a GameObject inches back (Left/Right/Back) after its been hit?
我使用 isKinematic = true 的剛體和 isTrigger isTrigger = true
isKinematic = true
的盒子對撞機。 在 object 與另一個碰撞后,我將 object 移動到碰撞后幾英寸處。 有沒有更好的方法來使用標准化來實現這一點? 這樣它會自動計算從 GameObject 到與之碰撞的 Box Collider 的距離,並將用戶放在它后面。 由於有時需要更改 x 值,有時需要更改其 z,因此這些值也可能為負數。 我所做的只是一個快速修復,如果值為負數,則無法正常工作。
using UnityEngine;
using System.Collections;
using UnityEngine;
public class CollisionDetector : MonoBehaviour
{
public GameObject PlayerPos;
public void OnTriggerEnter(Collider col)
{
if(col.gameObject.tag == "CollideWithCam")
{
Debug.Log("HIT");
StartCoroutine(MoveBack());
}
}
IEnumerator MoveBack()
{
yield return new WaitForSeconds(0.1f);
PlayerPos.transform.position = new Vector3(PlayerPos.transform.position.x-1f, PlayerPos.transform.position.y, PlayerPos.transform.position.z-1f);
}
}
您只需計算 object 相對於障礙物的 position。 之后,您可以根據需要修改相對向量並將其應用於播放器。 像這樣的東西:
// No need to store GameObject when only Transform is needed.
[SerializeField]
private Transform player;
// You can use [SerializeField] attribute to modify this value via inspector
// and keep it private.
[SerializeField]
private float bounceDistance = 1;
private void OnTriggerEnter(Collider other)
{
// Instantly return if 'other' object has wrong tag.
// 'CompareTag' is mush faster than '==' operator.
if (other.CompareTag("CollideWithCam")) return;
// Might consider this value something like 'direction from the hit':
Vector3 relativePosition = other.transform.position - transform.position;
relativePosition = relativePosition.normalized * bounceDistance;
// It is not clear what you trying to achieve.
// Place the player behind the bounced object?
StartCoroutine(MovePlayerTo(transform.position + relativePosition));
// Or place the player behind the obstacle?
StartCoroutine(MovePlayerTo(other.transform.position - relativePosition));
}
// Moving player to some position.
private IEnumerator MovePlayerTo(Vector3 position)
{
// Defining variable with meaningful name instead of using magic value directly.
float delay = 0.1f;
yield return new WaitForSeconds(delay);
player.position = position;
}
請注意,在示例中,玩家始終出現在距游戲對象中心的預定義距離處。 如果您需要確切的碰撞點,最好禁用觸發器並使用OnCollisionEnter
:
private void OnCollisionEnter(Collision other)
{
Vector3 hitDirection = other.contacts[0].normal;
Vector3 hitPoint = other.contacts[0].point;
StartCoroutine(MovePlayerTo(hitPoint - hitDirection));
}
(您還需要忽略不相關的碰撞)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.