Skip to content

Instantly share code, notes, and snippets.

@runewake2
Created November 6, 2016 02:14
Show Gist options
  • Save runewake2/d50a4c4825f7853c947516bc59d44fb6 to your computer and use it in GitHub Desktop.
Save runewake2/d50a4c4825f7853c947516bc59d44fb6 to your computer and use it in GitHub Desktop.
An excerpt from the World of Zero Physics Playground. A 2D controller to handle boxes accurately falling into precise holes.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody2D))]
public class FallingBox : MonoBehaviour {
public float width = 1;
private new Rigidbody2D rigidbody;
private RaycastHit2D hit;
public Transform origin;
// Use this for initialization
void Start () {
rigidbody = GetComponent<Rigidbody2D>();
width = 3.5f * 0.8f;
}
// Update is called once per frame
void FixedUpdate () {
if (!Mathf.Approximately(rigidbody.velocity.x, 0))
{
float rayDirection = rigidbody.velocity.x > 0 ? -1 : 1;
Ray2D ray = new Ray2D(origin.position, new Vector2(rayDirection, -1));
hit = Physics2D.Raycast(ray.origin, ray.direction, width*2);
float halfWidth = width*0.5f;
Debug.Log(hit.distance);
float collidedLength = origin.position.x - hit.point.x;
if (collidedLength > halfWidth)
{
Vector3 targetPosition = new Vector3(hit.point.x + halfWidth, transform.position.y, transform.position.z);
this.transform.position = targetPosition;
Debug.Log("Locking the box: " + targetPosition);
}
}
}
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawLine(origin.position, hit.point);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment