首页 > 解决方案 > transform.position 不移动玩家

问题描述

我有一个Player(由圆柱体制成,一些和FirstCam,用于在按下某个键时切换视图 - 没关系),它位于立方体上(足够宽,可以在上面散步)。立方体下面没有别的东西。SecondCamThirdCam

这是它的样子:

在此处输入图像描述

这是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 中输出一些东西以查看它是否有效,并且输出已打印,但仍然没有发生瞬移。

可能是什么问题呢?

标签: c#unity3d

解决方案


推荐阅读