Gravity

From Unify Community Wiki
Revision as of 10:42, 5 January 2009 by Opless (Talk | contribs)

Jump to: navigation, search

Provides a relatively accurate simulation of body-to-body gravity (i.e. plantary gravity).


You'll want to set Range to a different value depending on the size of your level, etc.

Gravity.js

<javascript> var range : float = 30.0;

function FixedUpdate () { var cols : Collider[] = Physics.OverlapSphere(transform.position, range); var rbs : Array = new Array(); for (c=0;c<cols.length;c++) { if (cols[c].attachedRigidbody && cols[c].attachedRigidbody != rigidbody) { var breaking :boolean = false; for (r=0;r<rbs.length;r++) { if (cols[c].attachedRigidbody == rbs[r]) { breaking=true; break; } } if (breaking) continue; rbs.Add(cols[c].attachedRigidbody); var offset : Vector3 = (transform.position - cols[c].transform.position); var mag: float = offset.magnitude; cols[c].attachedRigidbody.AddForce(offset/mag/mag * rigidbody.mass); } } }</javascript>

Gravity.cs

[oPless]

<CSharp> using UnityEngine; using System.Collections.Generic;

public class Gravity : MonoBehaviour { public static float range = 1000;

// Use this for initialization void Start () {

}

// Update is called once per frame void FixedUpdate () { Collider[] cols = Physics.OverlapSphere(transform.position, range); List <Rigidbody> rbs = new List<Rigidbody>();

foreach(Collider c in cols) { Rigidbody rb = c.attachedRigidbody; if(rb != null && rb != rigidbody) {

if(rbs.Contains(rb)) { continue; }

rbs.Add(rb); Vector3 offset = transform.position - c.transform.position; rb.AddForce( offset / offset.sqrMagnitude * rigidbody.mass); } } } }


</CSharp>

Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox