Using Unity 3.3. visual studio express 2010. and c#.
I need to make a script that will be attached to an object. This object will create its own gravity field that will attract- repel all objects in the environment.
Unfortunately I'm not sure how to do this due to unitys physics. would I need the object to overide all other objects? do I overide unitys main physics ? hows this work? Or am I overcomplicating things when its a simple script?
No I do not want to add a rigig body so the object falls with gravity, it must CREATE gravity that is a lot more powerfull.
Cheers
UPDATE!
public float radius = 5.0f;
public float power = -20f;
void Start ()
{
//GameObject gravityObject = GameObject.FindGameObjectWithTag("GravitySwell");
//gravSlime = gravityObject.transform;
}
void Update ()
{
Vector3 explosionPos = transform.position;
Collider[] colliders = Physics.OverlapSphere(explosionPos, radius, 3);
foreach (Collider hit in colliders)
{
if (!hit)
{
continue;
}
if (hit.rigidbody)
{
hit.rigidbody.AddExplosionForce(power, explosionPos, radius, 3);
}
}
}
}
this works as it adds a negative force that attracts the object. Problem is that when the attractive object this script is assigned to is in mid air. any objects caught fly towards it, but then seems to fall only to be attracted again. Any hints as to why ?
I was thinking something like this, but nothing happens:
Vector3 direction = this.transform.position - hit.transform.position;
direction.Normalize();
//hit.rigidbody.AddExplosionForce(power, explosionPos, radius, 3);
//hit.transform.position.;
hit.rigidbody.isKinematic = false;
hit.rigidbody.AddForce(direction);
UPDATE:: Ok I was trying this out, its seems to work well but its attached to the object that is being attracted. Also I was hoping if someone had a better idea?
public void OnCollisionEnter(Collision col)
{
if(col.gameObject.tag == "GravitySwell")
{
Debug.Log("i hit it!!!");
rigidbody.velocity = Vector3.zero;
}
}
what you can do is add a collision box that unity has as a component to add to any gameObjects and then you check if anything enters that collision box and add force to the object that is colliding. i will get you sample code if needed.
//edit
you can add your own gravity to a script and have your own function for adding force to make it move in a direction but just so you know you can change how much gravity a rid. body does
but if you want to do your own gravity you can do
bool grounded = false;
void gravity(){
gameObject.trasform.position.x -= gravity
}
void onCollisionEnter(collision c){
//check and see what you are colliding with and if its the ground then set grounded to true and that will get you falling gravity. there is more you can do for more adv. gravity but ill leave that up to you
}
edit*
if i get what your saying about sticking to an object what you need to do is make the object the parent of the object that needs to stick to it