【发布时间】:2022-07-07 23:47:50
【问题描述】:
我正在制作一个可以爬上无限楼梯的游戏。
首先,我编写了可以通过操纵玩家的 Z 位置运行无限走廊的原型代码,它可以工作。
然后,我更改该代码以操纵玩家的 Y 位置。
void FixedUpdate()
{
this.handleInfiniteHallway();
}
private void handleInfiniteHallway()
{
if (this.isPlayerOutOfBounds())
{
float posYmod = HALLWAY_HEIGHT;
if (this.player.position.y > MAX_Y_BOUND)
{
posYmod *= -1;
}
this.player.position = new Vector3(this.player.position.x, this.player.position.y + posYmod, this.player.position.z);
Debug.Log("Player Y position: " + this.player.position.y);
}
}
private bool isPlayerOutOfBounds()
{
return this.player.position.y > MAX_Y_BOUND || this.player.position.y < MIN_Y_BOUND;
}
使用此代码,游戏会发生故障,就像玩家同时拥有两个 Y 位置一样。
我发现了什么:
- 如果我使用
FixedUpdate(),玩家在游戏视图中的位置不会改变,但debug.Log表示玩家Y 位置已经改变。如果玩家到达Y_Bound,if(this.isPlayterOutOfBounds())中的代码将无限执行。 - 如果我使用
Update()而不是FixedUpdate(),玩家的位置在游戏视图和debug.Log中会发生变化,但有时玩家会在原始位置和重新定位的位置之间来回闪烁。如果玩家到达Y_Bound,if(this.isPlayterOutOfBounds())中的代码将无限执行。
这是链接到玩家游戏对象的Player Controller 脚本
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class PlayerController : MonoBehaviour
{
[SerializeField] private float playerSpeed = 10.0f;
[SerializeField] private float jumpHeight = 1.0f;
[SerializeField] private float gravityValue = -9.81f;
private bool isFlashLightOn = true;
public GameObject lightSource;
private CharacterController controller;
private Vector3 playerVelocity;
private bool groundedPlayer;
private InputManager inputManager;
private Transform cameraTransform;
private void Start()
{
controller = gameObject.GetComponent<CharacterController>();
inputManager = InputManager.Instance;
cameraTransform = Camera.main.transform;
lightSource.gameObject.SetActive(true);
isFlashLightOn = true;
}
void FixedUpdate()
{
groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector2 movement = inputManager.GetPlayerMovement();
Vector3 move = new Vector3(movement.x, 0, movement.y);
move = cameraTransform.forward * move.z + cameraTransform.right * move.x;
move.y = 0f;
controller.Move(move * Time.deltaTime * playerSpeed);
// Changes the height position of the player..
if (inputManager.PlayerJumped() && groundedPlayer)
{
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
}
void Update()
{
if (inputManager.PlayerFlashLightOn())
{
isFlashLightOn = !isFlashLightOn;
lightSource.gameObject.SetActive(isFlashLightOn);
}
}
}
【问题讨论】:
-
您的
this.player指的是什么?GameObject或transform附加到游戏对象? -
我相信它是附加到游戏对象的变换。
public Transform player; -
是的,它可能是。 GameObject 没有位置属性,所以会报错。
标签: unity3d