问题描述
我正在创建一个马里奥克隆体,我需要在跳跃时保持玩家向前的动力,然后在着陆时保持前进的动力。我无法弄清楚如何实现这一目标。每次我着陆时,玩家都必须再次建立动力。任何想法如何解决这个问题?我尝试了几种解决方案都无济于事。我认为这与我在向左或向右按住时向玩家添加力和加速度的方式有关。不确定虽然任何帮助都会非常感激。提前致谢。
这是我的代码:
Animator animator;
Rigidbody2D rb;
bool isGrounded;
public float moveSpeed;
public Vector2 acceleration;
public float jumpHeight;
public float lowjumpMultiplier;
public Transform groundCheckM;
public Transform groundCheckL;
public Transform groundCheckR;
public float storedValue;
void Start()
{
animator = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
transform.eulerAngles = new Vector3(0,0);
}
private void Update()
{
if
((Physics2D.Linecast(transform.position,groundCheckM.position,1 << LayerMask.NametoLayer("Floor/Platforms"))) || //Check if grounded
(Physics2D.Linecast(transform.position,groundCheckL.position,1 << LayerMask.NametoLayer("Floor/Platforms"))) ||
(Physics2D.Linecast(transform.position,groundCheckR.position,1 << LayerMask.NametoLayer("Floor/Platforms"))))
{
isGrounded = true;
animator.SetBool("Jump",false);
}
else
{
isGrounded = false;
}
animator.SetFloat("Walk",rb.veLocity.x); //Set animation float to x veLocity
if (rb.veLocity.x <= 0.03f && rb.veLocity.x >= -0.03f && isGrounded) //Play "Idle" animation
{
animator.Play("Mario_Idle");
}
if (rb.veLocity.x >=4 || rb.veLocity.x <=-4)
{
animator.speed = Mathf.Abs(rb.veLocity.x / 5.5f); //Increase speed of walking animation with player's walking speed
}
}
void FixedUpdate()
{
if (Input.GetKey("d") || Input.GetKey("right")) //Move player to the right
{
rb.AddForce(acceleration * rb.mass);
transform.rotation = Quaternion.Euler (0,0);
}
else if (Input.GetKey("a") || Input.GetKey("left")) //Move player to the left
{
rb.AddForce(-acceleration * rb.mass);
transform.rotation = Quaternion.Euler(0,180,0);
}
if (rb.veLocity.x >= 10)
{
rb.veLocity = new Vector2(10,rb.veLocity.y); //Cap player speed at 10 when moving right
}
else if (rb.veLocity.x <= -10)
{
rb.veLocity = new Vector2(-10,rb.veLocity.y); //Cap player speed at 10 when moving left
}
if (Input.GetKey("space") && isGrounded) //Player jump
{
rb.veLocity += new Vector2(rb.veLocity.x,jumpHeight);
animator.SetBool("Jump",true);
}
}
}
解决方法
我觉得自己很笨,但答案在物理材料中。一旦我降低了摩擦力,它就可以让跳跃的动力传递到玩家的跑步速度中。我想这是一个很好的提醒,可以直接在 Unity 及其内置物理系统中进行修补。
,如果你想在跳跃时保持你的动力,你可以将它存储在一个变量中,直到它达到最大值,或者你松开键。
float acceleration;
float accelFactor = 0.6f;
float deAccelFactor = 1f;
bool jumping; //you should set it to true when jumping and false,when not.
Rigidbody2D rb;
void Start(){
rb = GetComponent<Rigidbody2D>();
}
void Update(){
if (Input.GetKeyDown(KeyCode.D))
{
Accelerate();
rb.AddForce(acceleration * rb.Mass);
}
else if (jumping)
{
rb.AddForce(acceleration * rb.Mass);
}
else
{
DeAccel();
}
}
void Accelerate(){
acceleration += accelFactor * Time.deltaTime;
acceleration = Mathf.Clamp(acceleration,maxAccel);
}
void DeAccel(){
acceleration -= deAccelFactor * Time.deltaTime;
acceleration = Mathf.Clamp(acceleration,maxAccel);
}
这是我推荐使用的,也就是说,如果我理解你的意思。