How to restart object position in Unity?
I have a problem with refreshing object position, the condition I want 开发者_如何学JAVAto make is pretty easy. If a game object moves too far by X axis, then restart its position where it was at the beginning
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. 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.
Change the condition to like this in restartPlayerPosition().
if(transform.position.x > 10 || transform.position.x < -10)
That's it. It will work.
Change your RestartPlayerPosition method with this:
void restartPlayerPosition()
{
if(transform.position.x > (startPos.x +10) || transform.position.x < (startPos.x - 10)
{
this.transform.position = startPos;
}
}
精彩评论