//BUG: We are currently missing inputs. Fix it by looking at this: https://answers.unity.com/questions/409507/eliminating-input-loss.html //Bug: When at full speed it is impossible to turn around //It happens because the velocity delta becomes 0 since no more velocity has to be added //The fix shouldn't just turn the velocity around, but should also make sure that the proper acceleration is being applied private void FixedUpdate() { if (inputLeft || inputRight) { float value = Mathf.Abs(rb.velocity.x / maxGroundVelocity); float currentTime = AnimationCurveExtension.ReverseEvaluate(curve, value); float newTime = currentTime + Time.deltaTime; float newVelocity = curve.Evaluate(newTime) * maxGroundVelocity; float velocityDelta = newVelocity - Mathf.Abs(rb.velocity.x); //This is a nasty solution to the above issue, but I guess it works if (velocityDelta == 0) { velocityDelta = 0.01f; } //Debug.Log("ReverseGetTime: " + currentTime + ", currentVelocity: " + rb.velocity.x + ", newVelocity: " + newVelocity + ", velocity delta: " + velocityDelta); Vector2 addVector = new Vector2(velocityDelta, 0); if (inputLeft) { rb.velocity -= addVector; } if (inputRight) { rb.velocity += addVector; } } //Clamp horizontal speed float clampedXSpeed = Mathf.Clamp(rb.velocity.x, -maxGroundVelocity, maxGroundVelocity); rb.velocity = new Vector2(clampedXSpeed, rb.velocity.y); if (inputJump) { Debug.Log("Got input"); } if (inputJump && onGround) { rb.AddForce(new Vector2(0, jumpForce)); } if (!onGround) { rb.AddForce(new Vector2(0, gravity)); } }
// Update is called once per frame private void Update() { float velocityTillZero = 0 - rb.velocity.x; //Add velocity according to acceleration curve if (Input.GetKey(KeyCode.A)) { rb.velocity -= new Vector2(AnimationCurveExtension.ReverseEvaluate(accelCurve, rb.velocity.x), 0); } //Remove acceleration according to decceleration curve, clamp to not get under 0 else if (velocityTillZero < 0) { float curveDeccel = AnimationCurveExtension.ReverseEvaluate(deccelCurve, rb.velocity.x); float clampedCurveDeccel = Mathf.Clamp(curveDeccel, 0, velocityTillZero); //rb.velocity += new Vector2(clampedCurveDeccel, 0); } //Add velocity according to acceleration curve if (Input.GetKey(KeyCode.D)) { rb.velocity += new Vector2(AnimationCurveExtension.ReverseEvaluate(accelCurve, rb.velocity.x), 0); } //Remove acceleration according to decceleration curve, clamp to not get under 0 else if (velocityTillZero > 0) { float curveDeccel = AnimationCurveExtension.ReverseEvaluate(deccelCurve, rb.velocity.x); float clampedCurveDeccel = Mathf.Clamp(curveDeccel, 0, velocityTillZero); //rb.velocity -= new Vector2(clampedCurveDeccel, 0); } if (Input.GetKeyDown(KeyCode.Space)) { rb.AddForce(new Vector2(0, jumpForce)); } if (!onGround) { rb.AddForce(new Vector2(0, gravity)); } }