I’m creating a side scroller where the Gravity of the player is a gameplay mechanic.
The initial gravity value is negative (falling downwards) and when the player presses the G key, the gravity changes to positive (floating upwards).
The script toggles a boolean value on/off when the G key is pressed. This part of the code works.
If the boolean is false(off) then the gravity should be -
if the boolean is true (on) then the gravity is equal to a antigrav variable (+gravity).
I can get the gravity to toggle so that the players gravity changes to positive, but I cannot change it back. Even though the boolean variable continues to toggle on/off.
[RequireComponent (typeof (Controller2D))]
public class Player : MonoBehaviour {
public float jumpHeight = 4;
public float timeToJumpApex = .4f;
float accelerationTimeAirborne = .2f;
float accelerationTimeGrounded = .1f;
float moveSpeed = 6;
public bool antigravTrue = false;
float antigrav;
float gravity;
float jumpVelocity;
Vector3 velocity;
float velocityXSmoothing;
Controller2D controller;
void Start () {
controller = GetComponent<Controller2D> ();
gravity = -(2 * jumpHeight)/Mathf.Pow (timeToJumpApex, 2);
antigrav = (2 * jumpHeight)/Mathf.Pow (timeToJumpApex, 2);
jumpVelocity = Mathf.Abs(gravity) * timeToJumpApex;
print ("Gravity: " + gravity + " Jump Velocity: " + jumpVelocity);
}
void Update(){
if (controller.collisions.above || controller.collisions.below){
velocity.y = 0;
}
Vector2 input = new Vector2(Input.GetAxisRaw ("Horizontal"), Input.GetAxisRaw ("Vertical"));
if (Input.GetKeyDown(KeyCode.Space) && controller.collisions.below){
velocity.y = jumpVelocity;
}
if (Input.GetKeyDown(KeyCode.Space) && controller.collisions.above){
velocity.y = -jumpVelocity;
}
if(Input.GetKeyDown(KeyCode.G)){
antigravTrue = !antigravTrue;
}
if(antigravTrue){
gravity = antigrav;
}
if(!antigravTrue){
gravity = gravity;
print ("its false");
}
float targetVelocityX= input.x * moveSpeed;
velocity.x = Mathf.SmoothDamp(velocity.x, targetVelocityX, ref velocityXSmoothing,(controller.collisions.below)?accelerationTimeGrounded:accelerationTimeAirborne);
velocity.y += gravity *Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}