Skip to content

Instantly share code, notes, and snippets.

@eduardonunesp
Created September 3, 2019 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eduardonunesp/d9fc3792100f276e0db727807a10c5e2 to your computer and use it in GitHub Desktop.
Save eduardonunesp/d9fc3792100f276e0db727807a10c5e2 to your computer and use it in GitHub Desktop.
Raycast 2D
using UnityEngine;
public class RayCast2DExample : MonoBehaviour
{
// Float a rigidbody object a set distance above a surface.
public float floatHeight; // Desired floating height.
public float liftForce; // Force to apply when lifting the rigidbody.
public float damping; // Force reduction proportional to speed (reduces bouncing).
Rigidbody2D rb2D;
void Start()
{
rb2D = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
// Cast a ray straight down.
RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up);
// If it hits something...
if (hit.collider != null)
{
// Calculate the distance from the surface and the "error" relative
// to the floating height.
float distance = Mathf.Abs(hit.point.y - transform.position.y);
float heightError = floatHeight - distance;
// The force is proportional to the height error, but we remove a part of it
// according to the object's speed.
float force = liftForce * heightError - rb2D.velocity.y * damping;
// Apply the force to the rigidbody.
rb2D.AddForce(Vector3.up * force);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment