問題のあるコードは次のとおりです。
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;
}
}
スクリプトはプレイヤーにマウントされます。プレイヤーが水平方向に静止した剛体のコライダーに遭遇した場合、移動ボタンを押し続けると、キャラクターが左右にピクピクすることがあります。同時に、position.xは非常に狭い範囲でジッターし、potion.yは非常に小さい速度で減少することが観察されています。
オブジェクトを左から右に反転する方法を変更してloaclscaleを変更するか、オブジェクトを移動する方法を速度の変更から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;
}
(初めてゲームを作った経験はあまりありません。もっと良い方法や理由がわかれば、コメント欄で指摘していただければと思います。)