public class PlayerMovement : MonoBehaviour
{
[SerializeField] float runSpeed = 5f;
[SerializeField] float jumpSpeed = 5f;
[SerializeField] float climbSpeed = 5f;
[SerializeField] Vector2 deathKick = new Vector2(10f, 10f);
[SerializeField] GameObject bullet;
[SerializeField] Transform gun;
Vector2 moveInput;
Rigidbody2D myRigidbody;
Animator myAnimator;
CapsuleCollider2D myBodyCollider;
BoxCollider2D myFeetCollider;
float gravityScaleAtStart;
bool isAlive = true;
void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
myAnimator = GetComponent<Animator>();
myBodyCollider = GetComponent<CapsuleCollider2D>();
myFeetCollider = GetComponent<BoxCollider2D>();
gravityScaleAtStart = myRigidbody.gravityScale;
}
void Update()
{
if(!isAlive )
{return;}
Die();
Run();
FlipSprite();
ClimbLadder();
OnFire();
}
void OnFire(InputValue value)
{
if (!isAlive)
{ return; }
Instantiate(bullet, gun.position, transform.rotation);
}
void OnMove(InputValue value)
{
moveInput = value.Get<Vector2>();
Debug.Log(moveInput);
}
void OnJump(InputValue value)
{
if (!myBodyCollider.IsTouchingLayers(LayerMask.GetMask("Ground")))
{
return;
}
if (value.isPressed)
{
myRigidbody.velocity += new Vector2(0f, jumpSpeed);
}
}
void Run()
{
Vector2 playerVelocity = new Vector2(moveInput.x * runSpeed, myRigidbody.velocity.y);
myRigidbody.velocity = playerVelocity;
bool playerHasHorizontalSpeed = Mathf.Abs(myRigidbody.velocity.x) > Mathf.Epsilon;
myAnimator.SetBool("isRunning", playerHasHorizontalSpeed);
}
void FlipSprite()
{
bool playerHasHorizontalSpeed = Mathf.Abs(myRigidbody.velocity.x) > Mathf.Epsilon;
if (playerHasHorizontalSpeed)
{
transform.localScale = new Vector2(Mathf.Sign(myRigidbody.velocity.x), 1f);
}
}
void ClimbLadder()
{
if (!myBodyCollider.IsTouchingLayers(LayerMask.GetMask("Climbing")))
{
myRigidbody.gravityScale = gravityScaleAtStart;
myAnimator.SetBool("isClimbing", false);
return;
}
Vector2 climbVelocity = new Vector2( myRigidbody.velocity.x, moveInput.y * climbSpeed);
myRigidbody.velocity = climbVelocity;
myRigidbody.gravityScale = 0f;
bool playerHasVerticalSpeed = Mathf.Abs(myRigidbody.velocity.y) > Mathf.Epsilon;
myAnimator.SetBool("isClimbing", playerHasVerticalSpeed);
}
void Die()
{
if(myBodyCollider.IsTouchingLayers(LayerMask.GetMask("Enemies" , "Hazards")))
{
isAlive = false;
myAnimator.SetTrigger("Dying");
myRigidbody.velocity = deathKick;
}
}
}
我正在学习Udemy的游戏开发课程- Tile Vania - Lecture 100。在添加OnFire()方法之前,上面的代码工作得很好。添加OnFire()方法后,我遇到了上述错误。OnFire()方法无法识别引用类型为InputValue的value参数。我不知道这里需要做什么。请帮助!
在Update()
中调用OnFire
方法时,需要将InputValue value
参数传递给该方法。
也就是说,它应该是这样的:
void Update()
{
if(!isAlive )
{return;}
Die();
Run();
FlipSprite();
ClimbLadder();
OnFire(value);
}
当然在定义value之前value
删除Update()中的OnFire()方法。在Input System
包中创建的方法不需要在Update方法中调用。例如,在Update()
中不调用OnMove()
或OnJump()
,而是调用它们的作品。