Skip to content

Instantly share code, notes, and snippets.

@caramelchocolate
Created January 9, 2020 09:12
Show Gist options
  • Save caramelchocolate/fb496ae0c4746de75b7d0b4332e3a5ee to your computer and use it in GitHub Desktop.
Save caramelchocolate/fb496ae0c4746de75b7d0b4332e3a5ee to your computer and use it in GitHub Desktop.
Floating in midair with a Rigidbody2D(Not gravityScale = 0)
using UnityEngine;
public class Floating : MonoBehaviour
{
protected Rigidbody2D rbody;
void Start()
{
this.rbody = GetComponent<Rigidbody2D>();
this.rbody.mass = 20;
this.rbody.gravityScale = 1f;
}
void FixedUpdate()
{
// rectify round-off error
float gravityForce = Mathf.Ceil(this.rbody.mass * this.rbody.gravityScale * -Physics2D.gravity.y * 1000000f) / 1000000f;
this.rbody.AddForce(Vector2.up * gravityForce);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment