繁体   English   中英

transform.position 在 Unity 中不起作用 3d

[英]transform.position not working in Unity 3d

我真的是 Unity 3d 的新手,我正在尝试重生我的角色。 答案似乎很简单,但我不明白为什么我的代码不起作用。 如果这是重复的,请告诉我。

public Vector3 PointSpawn;

void Start()
{
    PointSpawn = gameObject.transform.position;
}

void Update()
{
    if (gameObject.transform.position.y < 10)
    {
       gameObject.transform.position = PointSpawn;   // This doesn't work

       // gameObject.transform.LookAt(PointSpawn);   ---> This DOES work ok
    }
}

并行脚本

public float HorizontalMove;
public float VerticalMove;
private Vector3 playerInput;

public CharacterController player;

public float MoveSpeed;
private Vector3 movePlayer;
public float gravity = 9.8f;
public float fallVelocity;
public float JumpForce;
public bool DoubleJump = false;

public Camera mainCamera;
private Vector3 camForward;
private Vector3 camRight;

void Start()
{
    player = GetComponent<CharacterController>();
}

void Update()
{
    HorizontalMove = Input.GetAxis("Horizontal");
    VerticalMove = Input.GetAxis("Vertical");

    playerInput = new Vector3(HorizontalMove, 0, VerticalMove);
    playerInput = Vector3.ClampMagnitude(playerInput, 1);

    CamDirection();

    movePlayer = playerInput.x * camRight + playerInput.z * camForward;

    movePlayer = movePlayer * MoveSpeed;

    player.transform.LookAt(player.transform.position + movePlayer);

    setGravity();

    PlayerSkills();

    player.Move(movePlayer * Time.deltaTime );
}

void CamDirection()
{
    camForward = mainCamera.transform.forward;
    camRight = mainCamera.transform.right;

    camForward.y = 0;
    camRight.y = 0;

    camForward = camForward.normalized;
    camRight = camRight.normalized;
}

void PlayerSkills()
{
    if (player.isGrounded && Input.GetButtonDown("Jump"))
    {
        fallVelocity = JumpForce;
        movePlayer.y = fallVelocity;
        DoubleJump = true;
    }
    else if (player.isGrounded == false && Input.GetButtonDown("Jump") && DoubleJump == true)
    {
        fallVelocity = JumpForce *2;
        movePlayer.y = fallVelocity;
        DoubleJump = false;
    }
}
    
void setGravity()
{
    if (player.isGrounded)
    {
        fallVelocity = -gravity * Time.deltaTime;
        movePlayer.y = fallVelocity;
    }
    else
    {
        fallVelocity -= gravity * Time.deltaTime;
        movePlayer.y = fallVelocity;
    }
}

提前致谢!

所以问题的答案不在评论中:

最初的问题是分配gameObject.transform.position = PointSpawn似乎什么都不做。 由于该行编写正确,因此该 gameObject 的gameObject一定已在其他地方被覆盖。

随着 OP 的动作脚本的添加,玩家的 position 在动作的Update function 中被覆盖。由于其他分配是在Update中完成的,调用顺序不能保证按预期工作。 修复是为了确保移动Update不是在新的 position 分配的框架内运行,或者将条件和分配移动到始终在Update之后运行的 function,无论脚本执行顺序如何, LateUpdate

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM