繁体   English   中英

我的播放器没有移动在 Unity 2d 中使用 transform.position

[英]My player is not moving Using transform.position in Unity 2d

我正在 Unity 中制作 2D 游戏。 所以我使用 trasform.position += movePos 类型代码在按下特定键时移动我的播放器。 我也做了一些动画。 播放器不动,动画仍在执行。 在我制作跳跃动画之前,一切正常。 但现在它不工作了。 有人可以建议我该怎么做。 我没有在 github 中创建代码库,所以我不能分享它。

在这里您可以观看正在发生的事情的视频:- https://1drv.ms/v/s!AnUoIDNJEoVSmQylzexBqmA1i8Ur?e=4FhJ5h

这是我的播放器控制代码,负责控制:-

using System.Collections;
using UnityEngine;

public class PlayerControls : MonoBehaviour
{
    #region variables
    // Private variables
    private float speed = 15f;
    [SerializeField]
    private bool isOnGround;
    private Quaternion leftMoveRotate = new Quaternion(0f, 180f, 0f, 1f);
    private Quaternion rightMoveRotate = new Quaternion(0f, 0f, 0f, 1f);

    // Public Variables
    public Animator playerAnimator;
    #endregion
    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("ground"))
        {
            isOnGround = true;
        }
    }

    private void Update()
    {
        float horizontalInput = Input.GetAxis("Horizontal");
        if (horizontalInput > 0)
        {
            DInput();
        }
        if (horizontalInput < 0)
        {
            AInput();
        }
        playerAnimator.SetFloat("isRunning", Mathf.Abs(horizontalInput));
        if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.LeftShift))
        {
            Jump();
        }
    }
    private void Jump()
    {
        if (isOnGround)
        {
            transform.position += new Vector3(0f, 4f, 0f); // Jump code
            isOnGround = false;
        }
    }
    private void DInput()
    {
        transform.rotation = rightMoveRotate;
        transform.position += new Vector3(0.5f, 0f, 0f) * speed * Time.fixedDeltaTime;
    }
    private void AInput()
    {
        transform.rotation = leftMoveRotate;
        transform.position -= new Vector3(0.5f, 0f, 0f) * speed * Time.fixedDeltaTime;
    }
}

我还有一个跟随播放器的相机代码,这里是:-

using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    public Transform player;
    public float offSetX = 5f;
    public float offSetY = 2.5f;
    private void FixedUpdate() {
        Vector3 tempPos = transform.position;
        tempPos.x = player.position.x;
        tempPos.x += offSetX;

        tempPos.y = player.position.y;
        tempPos.y += offSetY;

        transform.position = tempPos;
    }
}

如果我从 Animator 中删除跳跃动画,所有控制都可以正常工作。 这是您可以查看的视频:- https://1drv.ms/v/s!AnUoIDNJEoVSmQ2k_o7Fbs0J5_8d?e=tJlayZ

您可能搞砸了并且没有在脚本中显示的一件事,是您在动画中记录了变换位置的变化,而动画与位置发生了混乱。

暂无
暂无

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

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