[英]How to restart object position in Unity?
I have a problem with refreshing object position, the condition I want to make is pretty easy.我在刷新对象位置时遇到问题,我想创建的条件非常简单。 If a game object moves too far by X axis, then restart its position where it was at the beginning
如果游戏对象在 X 轴上移动得太远,则重新开始它在开始时的位置
My code我的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float playerSpeed = 5.0f;
private Rigidbody playerRb;
private Vector3 startPos;
// Start is called before the first frame update
void Start()
{
playerRb = GetComponent<Rigidbody>();
startPos = GameObject.Find("Player").transform.position;
}
void restartPlayerPosition()
{
if(transform.position.x > 10 || transform.position.x < 10){
this.transform.position = startPos;
}
}
// Update is called once per frame
void Update()
{
float horizontalnput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
playerRb.AddForce(Vector3.forward * playerSpeed * verticalInput);
playerRb.AddForce(Vector3.right * playerSpeed * horizontalnput);
restartPlayerPosition();
}
}
But instead of move back and forth, it rotates, and I don't know why.但是它不是来回移动,而是旋转,我不知道为什么。 The thing I know, is that something wrong happens when I call startPos in the start() method, It is trying to refresh location immediately instead of looking on if statement condition first.
我知道的是,当我在 start() 方法中调用 startPos 时发生了错误,它试图立即刷新位置,而不是先查看 if 语句条件。 Do I miss something?
我想念什么吗?
I've also tried to find position of an object by using this method我还尝试使用此方法查找对象的位置
gameObject.transform.position = sartPos
No errors, but won't work as I wanted it to没有错误,但不会像我想要的那样工作
I think you forget the minus for the position to -10 < x < 10.我想你忘记了位置的负号为 -10 < x < 10。
Change the condition to like this in restartPlayerPosition().在 restartPlayerPosition() 中将条件更改为这样。
if(transform.position.x > 10 || transform.position.x < -10)
That's it.而已。 It will work.
它会起作用。
Change your RestartPlayerPosition method with this:用这个改变你的 RestartPlayerPosition 方法:
void restartPlayerPosition()
{
if(transform.position.x > (startPos.x +10) || transform.position.x < (startPos.x - 10)
{
this.transform.position = startPos;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.