我已经在这里工作了几个小时,还没有找到解决方案。一旦玩家到达最终目标,我希望玩家匹配最终位置并停止移动。 ![替代文字] [1]
我考虑让玩家成为最终目标的孩子,但是没有能够让任何事情发挥作用。
这是我的剧本。
public float speed = 10;
public float turnSpeed = 10;
public float maxVelocityChange = 10;
public float gravity = 10;
public bool isAlive;
public Text Score;
public int CollectibleValue;
//sounds
private AudioSource source;
public AudioClip Spark;
private bool grounded;
private Rigidbody _rigidbody;
private Transform PlayerTransform;
// Use this for initialization
void Start () {
StartLevel ();
CollectibleValue = 0;
}
public void StartLevel(){
PlayerTransform = GetComponent<Transform> ();
_rigidbody = GetComponent<Rigidbody> ();
_rigidbody.useGravity = false;
_rigidbody.freezeRotation = true;
isAlive = true;
source = GetComponent<AudioSource> ();
}
// Update is called once per frame
void FixedUpdate ()
{
if (isAlive) {
PlayerTransform.Rotate (0, (Input.GetAxis ("Horizontal") * turnSpeed * Time.deltaTime), 0);
Vector3 targetVelocity = new Vector3 (0, 0, speed * Time.deltaTime);
targetVelocity = PlayerTransform.TransformDirection (targetVelocity);
targetVelocity = targetVelocity * speed;
Vector3 velocity = _rigidbody.velocity;
Vector3 velocityChange = targetVelocity - velocity;
velocityChange.x = Mathf.Clamp (velocityChange.x, -maxVelocityChange, maxVelocityChange);
velocityChange.z = Mathf.Clamp (velocityChange.z, -maxVelocityChange, maxVelocityChange);
velocityChange.y = 0;
_rigidbody.AddForce (velocityChange, ForceMode.VelocityChange);
_rigidbody.AddForce (new Vector3 (0, -gravity * _rigidbody.mass, 0));
}
Score.text = CollectibleValue.ToString ();
}
void OnTriggerEnter(Collider Triggers) {
if (Triggers.tag == "Endgoal") {
isAlive = false;
// Here is where the player needs to stop and match the position of the end goal.
}
搜索之后,我发现了我认为的答案,我为目标变换了一个公共变量,并使用了这行代码。
void OnTriggerEnter(Collider Triggers) {
if (Triggers.tag == "Endgoal") {
isAlive = false;
PlayerTransform.transform.Translate (target.transform.position);
现在问题是,玩家被移动到不属于目标的位置并且玩家仍然向前移动。 此外,如果布尔是“活着”的话。是假的,为什么前进运动还在发生?
答案 0 :(得分:1)
Translate
将GameObject
移动给定的向量,而不是移动给定的向量。 See the documentation.
您可以通过设置GameObject
将transform.position
移动到给定位置。在你的情况下
void OnTriggerEnter(Collider Triggers)
{
if (Triggers.tag == "Endgoal")
{
isAlive = false;
PlayerTransform.transform.position = target.transform.position;
}
}
关于你问题的isAlive
部分,你已经为对象添加了力/速度,所以即使你停止添加力量,它仍在移动。如果希望它停止移动,请将其速度设置为零。
_rigidbody.velocity = Vector3.zero;
_rigidbody.angularVelocity = Vector3.zero;