Hi, I am trying to achieve realistic movements on my object for which I have been writing a custom gravity (with gravity Switched-Off on the RigidBody Component) and velocity script, but my gravity does not act properly. Even if I Switch-On the gravity in the RigidBody Component, My gravity and jump do not work.
My gravity(Scripted or from the editor) and Jump seems to work properly when I do not implement Movements. I have also tried reducing Drag below zero and yet my gravity and jump do not work. Here are the Scripts -
Physics.cs -
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace CustomPhysics
{
public class PhysicsClass : MonoBehaviour
{
private static PhysicsClass _physicsInstance;
public static PhysicsClass PhysicsInstance
{
get
{
if (_physicsInstance == null)
{
_physicsInstance = GameObject.FindObjectOfType<PhysicsClass>();
}
return _physicsInstance;
}
}
//gravity fields
private Vector3 _gravityVector;
private float _jumpAcceleration;
private float accelerationDueToGravity;
//movement fields
private float moveAcceleration;
private float friction;
private Vector3 _moveVector;
private void Awake()
{
moveAcceleration = 5;
friction = 1.5f;
accelerationDueToGravity = 9.8f;
}
public float JumpAcceleration
{
get
{
_jumpAcceleration = 3;
return _jumpAcceleration;
}
}
public Vector3 GravityVector
{
get
{
_gravityVector = Vector3.down * accelerationDueToGravity;
return _gravityVector;
}
}
public Vector3 MoveVector
{
get
{
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Vertical");
_moveVector = (new Vector3(x, 0, y) * moveAcceleration) / friction;
return _moveVector;
}
}
}
}
GravityAndVelocity.cs -
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static CustomPhysics.PhysicsClass;
public class GravityAndVelocity: MonoBehaviour
{
private Rigidbody RB;
private Transform objectTransform;
private float heightFactor;
private void Start()
{
RB = gameObject.GetComponent<Rigidbody>();
objectTransform = gameObject.GetComponent<Transform>();
heightFactor = 1.75f;
}
private void FixedUpdate()
{
//RB.drag = -100;
if (objectTransform.position.y > 0.1f)
{
gravity();
if (Input.GetKey(KeyCode.Space) && objectTransform.position.y < heightFactor)
{
RB.velocity = Vector3.up * PhysicsInstance.JumpAcceleration; // * Time.time;
}
}
RB.velocity = (PhysicsInstance.MoveVector);
}
void gravity()
{
RB.AddForce(PhysicsInstance.GravityVector);
}
}
So, What have I been doing wrong? Please, kindly Explain.