我是Unity和C#的新手。我正在努力开发自己的第一款游戏,很多语法使我感到困惑。我试图在按下“ a”或“ d”或方向键时用力在x轴上移动我的精灵,但看来我的精灵没有以恒定的速度移动。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class playerMovement : MonoBehaviour
{
public float vel = .5f;
public float jumpVel = 10f;
public bool isGrounded = false;
private Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = transform.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
//Vector3 move = new Vector3(Input.GetAxisRaw("Horizontal"), 0f,0f);
//transform.position += move * Time.deltaTime * vel;
if(Input.GetAxisRaw("Horizontal") == 1){
rb.AddForce(Vector2.right*vel, ForceMode2D.Force);
}else if(Input.GetAxisRaw("Horizontal") == -1){
rb.AddForce(Vector2.right*-vel, ForceMode2D.Force);
}
if(Input.GetKeyDown(KeyCode.Space) && isGrounded == true){
rb.velocity = Vector2.up * jumpVel;
}
}
}
这是因为您正在使用rb.AddForce向其添加力量,它会在每次播放时增加速度,以便玩家移动,我建议使用CharacterMovement组件,但是如果要使用Rigidbody2d,则是最佳解决方案我能想到的是:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class playerMovement : MonoBehaviour
{
public float vel = .5f;
public float jumpVel = 10f;
public bool isGrounded = false;
private Rigidbody2D rb;
public float maxbel = 10f;
// Start is called before the first frame update
void Start()
{
rb = transform.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
//Vector3 move = new Vector3(Input.GetAxisRaw("Horizontal"), 0f,0f);
//transform.position += move * Time.deltaTime * vel;
if(Input.GetAxisRaw("Horizontal") == 1 &&rb.velocity.x<=maxvel){
rb.AddForce(Vector2.right*vel, ForceMode2D.Force);
}else if(Input.GetAxisRaw("Horizontal") == -1 && rb.velocity.x>=-maxvel){
rb.AddForce(Vector2.right*-vel, ForceMode2D.Force);
}
if(Input.GetKeyDown(KeyCode.Space) && isGrounded == true){
rb.velocity = Vector2.up * jumpVel;
}
}
}
所以,在这个答案中,浮子maxvel(代表最大速度),这个浮子用于知道您想要的偶极子速度(您应该自己进行调整,我只是为代码工作提供了一些参考),我还调用rb.velocity.x来检查水平轴上的实际速度,因此我决定不直接更改该速度,因为那样会使该速度从0变为您放置的速度,使用addforce使其工作平稳;] >