如何使用RigidBody2D Velocity阻止角色感觉像在冰上?
本文关键字:感觉 角色 RigidBody2D 何使用 Velocity | 更新日期: 2023-09-27 18:08:31
我目前使用RB2D速度移动,但我不能让它停止滑动后,我已经完成按下按钮。感觉就像《马里奥》中的冰关卡。我该如何阻止角色到处滑动?
我的代码是:void Movement() {
if (Input.GetAxisRaw ("Horizontal") > 0.1) {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (speed, GetComponent<Rigidbody2D> ().velocity.y);
}
if (Input.GetAxisRaw ("Horizontal") < -0.1) {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (-speed, GetComponent<Rigidbody2D> ().velocity.y);
}
if (Input.GetAxisRaw ("Vertical") > 0.5 && grounded) {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, jumpHeight);
}
}
我的速度设置为5,跳跃高度设置为10并且我的播放器上同时有box collider和RigidBody2D
感谢您的帮助
你可以在按下键时使用变换来移动对象,直接移动它而不使用物理。
同样使用速度,当你不按任何按钮停止移动物体时,你可以将其设置为0.0f。
crabcrabcam现在使用:
void Movement() {
if (Input.GetAxisRaw ("Horizontal") > 0.1) {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (speed, GetComponent<Rigidbody2D> ().velocity.y);
} else if (Input.GetAxisRaw ("Horizontal") < -0.1) {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (-speed, GetComponent<Rigidbody2D> ().velocity.y);
} else if (Input.GetAxisRaw("Horizontal") == 0 && grounded) {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (Vector2.zero, GetComponent<Rigidbody2D> ().velocity.y);
}
if (Input.GetAxisRaw ("Vertical") > 0.5 && grounded) {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, jumpHeight);
}
}
这使得它在空中漂浮,但在地面时它会响应性地停止:)
将else if添加到第二个if语句中,然后再添加一个else语句来停止播放器的移动。
if (Input.GetAxisRaw("Horizontal") > 0.1)
{
Move right
}
else if (Input.GetAxisRaw("Horizontal") < -0.1)
{
Move left
}
else
{
Stop moving/Vector2.zero;
}
也许像这样:
void Movement()
{
if (Input.GetAxisRaw("Horizontal") > 0.1)
{
GetComponent<Rigidbody2D>().velocity = new Vector2(speed, GetComponent<Rigidbody2D>().velocity.y);
}
else if (Input.GetAxisRaw("Horizontal") < -0.1)
{
GetComponent<Rigidbody2D>().velocity = new Vector2(-speed, GetComponent<Rigidbody2D>().velocity.y);
}
else
{
GetComponent<Rigidbody2D>().velocity = Vector2.zero;
}
if (Input.GetAxisRaw("Vertical") > 0.5 && grounded)
{
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jumpHeight);
}
}
您应该使用Input.GetAxis("Horizontal")
。下面是一个简单的代码示例:
public float maxSpeed = 10f;
public float jumForce = 700f;
public Transform groundCheck;
float groundRadius = 0.2f;
public LayerMask whatIsGrounded;
bool grounded = false;
void FixedUpdate()
{
grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGrounded)
float move = Input.GetAxis("Horizontal");
rigidbody2D.velocity = new Vector2(move * maxSpeed, rigidbody2D.velocity.y);
}
void Update()
{
if(grounded && Input.GetKeyDown(KeyCode.Space))
{
rigidbody2D.AddForce(new Vector2(0, jumpForce));
}
}