【问题标题】:Player teleports instead of moving smoothly玩家传送而不是平稳移动
【发布时间】:2019-10-14 19:28:34
【问题描述】:

当我第一次对播放器的运动进行编码时,一切都很好,除了一件事:当它与墙壁碰撞时,它会振动/抖动。因此,我将使用的 transform.Translate() 替换为 Rigidbody2D.Moveposition();它就像一个魅力。但是现在每当我移动它时,它都会振动/有点传送,并且移动不顺畅。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Player : MonoBehaviour
{


    private Rigidbody2D rigidbody2d;


    float MovementX = 0;
    float MovementY = 0;

    public float Speed = 5f;


    void Start()
    {
        rigidbody2d = GetComponent<Rigidbody2D>();


    }


    void Update()
    {




        if (MovementX < 0)
            transform.localScale = new Vector2(-1, 1);
        if (MovementX > 0)
            transform.localScale = new Vector2(1, 1);


        //transform.Translate(Movement);
        //rigidbody2d.MovePosition(Movement);
        //rigidbody2d.AddForce(Movement * Speed);



    }

    private void FixedUpdate()
    {
        MovementX = Input.GetAxis("Horizontal") * Speed * Time.deltaTime;
        MovementY = Input.GetAxis("Vertical") * Speed * Time.deltaTime;

        //MovementX = movementJoystick.Horizontal * Speed * Time.deltaTime;
        //MovementY = movementJoystick.Vertical * Speed * Time.deltaTime;

        Vector2 Movement = new Vector2(transform.position.x + MovementX, transform.position.y + MovementY);
        rigidbody2d.MovePosition(Movement);
    }


}

正如我之前所说,玩家应该可以平稳移动,但事实并非如此。如果您愿意,我可以尝试链接该游戏的视频。

提前致谢。

【问题讨论】:

  • 您可以尝试将速度设置为 velocity = new Vector2(MovementX, MovementY); 而不是 MovePosition
  • 试试 Time.fixedDeltaTime
  • 另外,对Input 的调用应该在Update 方法中。来自the documentation:“还要注意,输入标志在更新之前不会重置。建议您在更新循环中进行所有输入调用。”

标签: c# unity3d


【解决方案1】:

Rigidbody2D 有一个称为速度的属性,如果您在类的更新中设置刚体的速度,这应该可以解决您的问题。代码可能如下所示:

rigidbody2d.velocity = new Vector2(MovementX, MovementY);;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多