出現該問題的代碼如下:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayController : MonoBehaviour
{
[Header("移動引數")]
public Vector2 currentVelocity;
public float xInput;
public float LRMoveForce;
private void Start()
{
pos = GetComponent<Transform>();
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
LRMovement();
}
private void LRMovement()
{
if (rb.velocity.x < 0)
{
faceDir = -1;
pos.rotation = Quaternion.Euler(0, 180, 0);
//transform.localScale = new Vector3(-1, 1, 1);
}
if (rb.velocity.x > 0)
{
faceDir = 1;
pos.rotation = Quaternion.Euler(0, 0, 0);
//transform.localScale = new Vector3(1, 1, 1);
}
xInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(xInput * LRMoveForce, rb.velocity.y);
currentVelocity = rb.velocity;
}
}
該腳本掛載在player上,當player在水平方向上遇到static剛體的collider時持續按下移動鍵可能會發生角色左右抽搐的情況,同時觀察到position.x會在極小范圍內抖動,potion.y會以極小的速率遞減,
無論是將物體左右翻轉的方式改為修改loaclscale,還是將物體移動的方式由修改velocity改為addforce均無法解決問題,
可行的解決方案:判斷物體朝向的代碼不放在rb.velocity.x的判斷下,修改后的代碼如下
private void LRMovement()
{
if (rb.velocity.x < 0)
{
faceDir = -1;
//pos.rotation = Quaternion.Euler(0, 180, 0);
//transform.localScale = new Vector3(-1, 1, 1);
}
if (rb.velocity.x > 0)
{
faceDir = 1;
//pos.rotation = Quaternion.Euler(0, 0, 0);
//transform.localScale = new Vector3(1, 1, 1);
}
xInput = Input.GetAxisRaw("Horizontal");
if (xInput < 0)
{
pos.rotation = Quaternion.Euler(0, 180, 0);
}
if (xInput > 0)
{
pos.rotation = Quaternion.Euler(0, 0, 0);
}
rb.velocity = new Vector2(xInput * LRMoveForce, rb.velocity.y);
currentVelocity = rb.velocity;
}
(第一次嘗試制作游戲,不是很有經驗,如果有更好的方法或者知道原因的也希望各位能在評論區指出,)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/222938.html
標籤:java
