我对Unity和C#没有经验。这段代码看起来是对的。我真的不知道我需要在这里放些什么来提供更多的上下文,所以如果需要的话,我会这样做
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace ModScripts
{
public class TeleporterScript : MonoBehaviour, IUseItem
{
public float maxRange = 5f;
[SerializeField]
private GameObject playerObject;
private Collider[] colliders;
private GameObject target;
private float distancia;
// UseItem executes right when player presses a specific key on keyboard
public void UseItem(Transform position, Quaternion rotation)
{
// playerObject is supposed to be the player that used the item
playerObject = position.gameObject;
Instantiate(gameObject, position.position, rotation);
CheckCollider();
}
void CheckCollider()
{
// Check the players using colliders
// layer 15 is player A
// layer 16 is player B
int layerMask = (1 << 15) | (1 << 16);
// Physics.OverlapSphere to make a limited range around the player
colliders = Physics.OverlapSphere(transform.position, maxRange, layerMask);
// Calculate distance between colliders[]
foreach (Collider collider in colliders)
{
if (collider.gameObject.layer != playerObject.layer)
{
// Calculate distance
distancia = Vector3.Distance(playerObject.transform.position, collider.transform.position);
// If distance is bigger than maxRange
if (distancia > maxRange)
{
break;
}
else
{
// Teleport to target
target = collider.gameObject;
Teleport(target);
}
}
}
}
void Teleport(GameObject target)
{
// Debug.Log says the intended target
Debug.Log(target.name);
float elevation = 0f;
// Get velocity of both karts
Vector3 currentVelocity = playerObject.GetComponent<Rigidbody>().velocity;
Vector3 targetVelocity = target.GetComponentInParent<Rigidbody>().velocity;
// Switch positions between kart that used item and target
Vector3 tempPosition = new Vector3(playerObject.transform.position.x, playerObject.transform.position.y + elevation, playerObject.transform.position.z);
playerObject.transform.position = new Vector3(target.transform.position.x, target.transform.position.y + elevation, target.transform.position.z);
target.transform.position = tempPosition;
// Maintain velocity of karts
playerObject.GetComponent<Rigidbody>().velocity = currentVelocity;
target.GetComponentInParent<Rigidbody>().velocity = targetVelocity;
}
}
}
上面的代码将使用物品的玩家传送到另一个玩家的位置,如预期的那样。然而,另一个玩家不改变位置,导致一个玩家在另一个玩家之上。我正在使用团结kartgame演示,如果它是任何重要的。
1条答案
按热度按时间wn9m85ua1#
你从父对象得到刚体,所以
target
不是目标的根对象,你需要移动根对象而不是这个target
。