I’m trying to simulate a cartoon-like physics, for a flappy birds learning project.
Player click: Immediately flap upwards
When going up (flap): Rotate upwards, to a certain extent
When falling: Rotate downwards, to a certain extent
Only way I can think of to do the rotation is to:
set the angularVelocity clockwise/counter clockwise, depending on velocity.y
and to constrain the rotation by clamping the Rigidbody2d.rotation, and setting the angularVelocity to 0f when exceeding the thresholds.
Here’s my code. Can someone let me know if this is the right way to do this (manipulate physics2d). Or is there a better way?
On a lower gravity scale, I’ve noticed some jerking/jittering when going up/down, but don’t know how to fix it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControllerMin : MonoBehaviour {
private Rigidbody2D rb;
public float flapUpVelocity = 5f;
public float angularVelocity = 200f;
public float maxRotateUpAngle = 20f;
public float maxRotateDownAngle = -20f;
private const float deltaY = 0.2f;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
Flap ();
SimulateRotation ();
}
void Flap()
{
if (Input.GetMouseButtonDown (0))
{
// Flap
rb.velocity = new Vector3 (0f, flapUpVelocity, 0f);
}
}
void SimulateRotation()
{
if (rb.velocity.y > deltaY)
{
// Going up. Rotate upwards.
rb.angularVelocity = angularVelocity;
}
else if (rb.velocity.y < -deltaY)
{
// Falling. Rotate downwards.
rb.angularVelocity = -angularVelocity;
}
ConstrainRotation ();
}
void ConstrainRotation()
{
if (rb.rotation > maxRotateUpAngle)
{
// Rotation exceeded max up.
// Stop angular velocity
rb.rotation = maxRotateUpAngle;
rb.angularVelocity = 0f;
}
else if (rb.rotation < maxRotateDownAngle)
{
// Rotation exceeded max down.
// Stop angular velocity
rb.rotation = maxRotateDownAngle;
rb.angularVelocity = 0f;
}
}
}
Here’s how it currently behaves:
Thanks!