我有一个 Player
(由圆柱体制成,一些 FirstCam
、SecondCam
和 ThirdCam
,用于在按下某个键时切换视图 - 没关系),它位于一个立方体上(足够宽,可以在上面散步)。立方体下面没有其他东西。
这是它的样子:
这是 Player
的结构:
这是 Player
的检查器:
我有以下脚本 ResetToInitial.cs
,附加到我的 Player
:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ResetToInitial : MonoBehaviour {
Vector3 pos;
void Start() {
pos = transform.position;
}
void Update() {
if (transform.position.y < -10) {
transform.position = pos;
}
}
}
还有一些移动脚本 PlayerMovement.cs
可以让他向上、向下、向左、向右、跳跃和冲刺。
这是PlayerMovement.cs
:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class PlayerMovement : MonoBehaviour {
public CharacterController controller;
Vector3 velocity;
bool isGrounded;
public Transform groundCheck;
public LayerMask groundMask;
public TextMeshPro State;
public TextMeshPro State2;
public TextMeshPro State3;
// Start is called before the first frame update
void Start() {
}
// Update is called once per frame
void Update() {
float groundDistance = 0.4f;
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0) {
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
float g = -20f;
float jumpHeight = 1f;
float speed = 6f;
if (Input.GetKey(KeyCode.LeftShift)) {
speed = 8f;
State.text = "running mode";
State2.text = "running mode";
State3.text = "running mode";
} else {
speed = 5f;
State.text = "walking mode";
State2.text = "walking mode";
State3.text = "walking mode";
}
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if (Input.GetButton("Jump") && isGrounded) {
velocity.y = Mathf.Sqrt(jumpHeight * -2f * g);
}
velocity.y += g * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
ResetToInitial.cs
旨在将 Player
传送到初始位置(回到立方体上,场景加载时记录的位置),在他跌落立方体后。问题是 transform.position
不会将玩家移动到任何地方。它不会做任何事情。我尝试在最后一个 if 中输出一些东西,看看它是否有效,并且输出被打印出来,但仍然没有发生瞬移。
可能是什么问题?