gpt4 book ai didi

c# - Unity 2D 中的卡顿运动

转载 作者:行者123 更新时间:2023-11-30 22:57:54 25 4
gpt4 key购买 nike

所以基本上我正在尝试让玩家移动系统像 RPG Maker 中的那样具有 8 个方向。不知何故,我成功了,但只是部分成功。当我试图突然改变前任的方向时。从上到左,角色结结巴巴,不想在不先释放所有键的情况下移动。

重力比例被禁用或更像是设置为 0,体型是动态的。

代码如下:

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

public class MoveChar : MonoBehaviour {

Rigidbody2D rigid;

public float Speed;

// Use this for initialization
void Start () {

rigid = GetComponent<Rigidbody2D>();

}

// Update is called once per frame
void Update () {

// float horiz = Input.GetAxis("Horizontal");

// float vert = Input.GetAxis("Vertical");

if(Input.GetKeyDown(KeyCode.W)) //________________________________________MOVING UP

{
rigid.velocity = new Vector2(rigid.velocity.x, 1 * Speed);
}
else if(Input.GetKeyUp(KeyCode.W))
{
rigid.velocity = new Vector2(0, 0);
}

if (Input.GetKeyDown(KeyCode.S)) //_______________________________________MOVING DOWN
{
rigid.velocity = new Vector2(rigid.velocity.x, -1 * Speed);
}
else if (Input.GetKeyUp(KeyCode.S))
{
rigid.velocity = new Vector2(0, 0);
}


if (Input.GetKeyDown(KeyCode.A)) //_______________________________________MOVING LEFT
{
rigid.velocity = new Vector2(-1 * Speed, rigid.velocity.y);
}
else if (Input.GetKeyUp(KeyCode.A))
{
rigid.velocity = new Vector2(0, 0);
}

if (Input.GetKeyDown(KeyCode.D)) //_______________________________________MOVING RIGHT
{
rigid.velocity = new Vector2(1 * Speed, rigid.velocity.y);
}
else if (Input.GetKeyUp(KeyCode.D))
{
rigid.velocity = new Vector2(0, 0);
}
}

最佳答案

使用 Input.GetAxis(axisName) 避免输入代码中的大小写冲突。此外,使用 AddForce 可以很好地与其他刚体一起玩。

Vector2 oldV = rigid.velocity;
float horiz = Input.GetAxis("Horizontal");
float vert = Input.GetAxis("Vertical");

Vector2 newV = new Vector2(horiz * Speed, vert * Speed);
rigid.AddForce(newV-oldV, ForceMode2D.Impulse);

或者,在抬起/按下按键时跟踪您自己的轴

public float horiz;
public float vert;

void Start() {
horiz = 0f;
vert = 0f;
if (Input.GetKey(KeyCode.A)) horiz -= 1f;
if (Input.GetKey(KeyCode.D)) horiz += 1f;
if (Input.GetKey(KeyCode.S)) vert -= 1f;
if (Input.GetKey(KeyCode.W)) vert += 1f;
}

void Update () {
Vector2 oldV = rigid.velocity;

if(Input.GetKeyDown(KeyCode.W)) vert += 1f;
else if(Input.GetKeyUp(KeyCode.W)) vert -= 1f;

if (Input.GetKeyDown(KeyCode.S)) vert -= 1f;
else if (Input.GetKeyUp(KeyCode.S)) vert += 1f;

if (Input.GetKeyDown(KeyCode.A)) horiz -= 1f;
else if (Input.GetKeyUp(KeyCode.A)) horiz += 1f;

if (Input.GetKeyDown(KeyCode.D)) horiz += 1f;
else if (Input.GetKeyUp(KeyCode.D)) horiz -= 1f;

Vector2 newV = new Vector2(horiz * Speed, vert * Speed);
rigid.AddForce(newV-oldV, ForceMode2D.Impulse);
}

关于c# - Unity 2D 中的卡顿运动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53306366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com