Making an object jump (without rigidbodies), while using enum + gravity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
private float groundSpeed = 0;
public float jumpSpeed;
private float speed;
public float gravity;
private float baseline;
private State playerState;
Vector3 moveDirection;
enum State
{
onGround,
jumping
};
void Start()
{
playerState = State.onGround;
baseline = this.transform.position.y;
moveDirection = new Vector3(0,0,0);
}
void Update()
{
switch (playerState)
{
case State.onGround:
DoOnGround();
if (Input.GetButtonDown("Jump"))
{
playerState = State.jumping;
}
break;
case State.jumping:
Jumping();
moveDirection.y = jumpSpeed;
if(transform.position.y <= baseline)
{
speed = groundSpeed;
playerState = State.onGround;
}
break;
}
transform.Translate(moveDirection * Time.deltaTime);
}
void DoOnGround()
{
transform.position = new Vector3(-6.8f,0,0); // This just sets it at the start to be on the left side of the screen rather than 0,0,0 which is the middle
}
void Jumping()
{
moveDirection.y -= gravity * Time.deltaTime;
}
}
This is what my code looks like, it's a mess and I'm kinda brain-fried right now, but essentially what happens is I either just shoot off into space, or now that I've added * Time.deltaTime to transform.translate's movedirection, I just ascend slowly into space.
I've looked at a few other examples but honestly I'm not sure why it's just shooting off rapidly into space , the y going in the 1000's, or in the case of my code here with the added deltatime, slowly ascends into the abyss. Should it not come down with moveDirection.y -= gravity * Time.deltaTime; ? I'm a bit confused and I've like re-worked my code a fair bit, but removed my comments so it doesn't look disgusting to view.
Your answer
Follow this Question
Related Questions
Jumping higher the more you hold space! 1 Answer
Need help with jumping 0 Answers
My Player Doesn't Jump 0 Answers
How can I modify this to allow jumping with space? 0 Answers
Player looses ability to jump further right player moves. 1 Answer