So I’m working out parts of what will eventually be an FPS involving up/down gravity changes for individual objects. I had previously worked out the gravity reversal for an object after it collided with another (the “energy blast” weapon that will change the gravity for enemies and objects) but now I’m trying to work on applying that to the player character and triggering it with a key stroke instead of weapon collision.
What seems to be happening is my test object representing the PC (a cylinder with a rigidbody and mesh collider, parented to a camera) doesn’t seem to be triggering the collision detection with the floor or ceiling (made of blocks of instances of two prefabs: “1st Floor Block” and “2nd Floor Block”).
So, basically, with the code below, when I hit “z” (“P1-SwitchGrav”), the cylinder will rise to the ceiling and “land” there, but when I hit “z” a second time, nothing happens.
The Debug Log prints out “Hit Z!”, “Rising!” & “Reversing!”, followed by 5 “Hit Z!”'s for some reason, but never a “Grounded!” note, which implies to me that the collision part of the code is not working (the reason “Gravity” and “Grounded” variables are public are so I can monitor them while running my test- and they both get set to false when I hit Z, but never revert to true).
So, what am i missing?
Here’s the code:
#pragma strict
public var gravity : boolean = true;
public var grounded : boolean = true;
function Start ()
{
}
function OnCollisionEnter(collision: Collision)
{
//Check to see if object is on floor or ceiling
if(collision.gameObject.name == "1st Floor Block" || collision.gameObject.name == "2nd Floor Block")
{
grounded = true;
Debug.Log ("Grounded!");
}
}
function Update ()
{
var value = Input.GetButton ("P1-SwitchGrav");
//Check to see if player has shifted their gravity
if (Input.GetButton ("P1-SwitchGrav"))
{
Debug.Log("Hit Z!");
//If gravity is active & object is on floor, disable gravity,
//indicate object is not on floor & start to reverse gravity
if (this.gravity == true && this.grounded == true)
{
Debug.Log("Rising!");
this.gravity = false;
this.grounded = false;
this.rigidbody.useGravity = false;
ReversedGravity();
}
//If gravity is disabled & object is on ceiling, reactivate gravity
//& indicate object is not on ceiling
if (this.gravity == false && this.grounded == true)
{
Debug.Log("Falling!");
this.gravity = true;
this.grounded = false;
this.rigidbody.useGravity = true;
}
}
}
function ReversedGravity ()
{
Debug.Log("Reversing!");
//When gravity is disabled, apply constant force towards ceiling
while (this.gravity == false)
{
rigidbody.AddForce(0, 2 , 0);
yield;
}
}