I’m still very new to unity, I have only been working with it for about two and a half months, I followed a short tutorial on creating Faux Gravity, almost everything works out perfectly, except jumping. I know that I need to use ray-casting to create the jump script, but I have no idea of how to do that, any help would be very appreciated.
public class PlayerMovement : MonoBehaviour
{
//Scripts
public PlanetScript PlanetScp;
//RigidyBody 2D
Rigidbody2D rb;
//bools
bool canMove = true;
// floats
public float MoveSpeed = 10f;
public float JumpSpeed = 10f;
//ints
public int NumberOfJumps = 2;
public int NumberOfJumpsDefault = 2;
public float MaxTimeInAir = 2;
void Start()
{
rb = GetComponent<Rigidbody2D>();
NumberOfJumps = NumberOfJumpsDefault;
}
void Update()
{
if (canMove)
{
if (Input.GetKey("d")) { Run(1); }
if (Input.GetKey("a")) { Run(-1); }
if (Input.GetKeyDown("space") && NumberOfJumps > 0)
{
Jump();
NumberOfJumps--;
}
if (rb.velocity.y == 0)
{
NumberOfJumps = NumberOfJumpsDefault;
}
}
}
void Run(int directionOnX)
{
Vector2 horizontal = new Vector2(directionOnX, rb.velocity.y).normalized;
rb.MovePosition(rb.transform.position + rb.transform.TransformDirection((horizontal) * MoveSpeed * Time.deltaTime));
}
void Jump()
{
Vector2 vertical = new Vector2(rb.velocity.x, JumpSpeed).normalized;
rb.velocity = rb.transform.position + rb.transform.TransformDirection((vertical) * MoveSpeed * Time.deltaTime);
rb.velocity = rb.transform.position + rb.transform.TransformDirection((-vertical) * MoveSpeed * Time.deltaTime);
//but theres a problem, if the player walks and jumps at the same time, he wont come back to the planet, give a try and tell me if u have any idea of how to fix that (: