Question by
UnityNewbie7 · Jan 29, 2021 at 03:37 AM ·
movementvector3jumpstate-machine
About states in coding (Idle, Walk, Jump etc
Hey, Im trying to make states for every state the player is currently is. I'm trying to make when the player is not touching any input he is idle if the player input is horizontal then the state is walking and if he is jump and state is jumping
as you can see I have few bugs and I dont know how to solve this. any help? also - you think it's better to make a bool system for the states? or it's good as enum?
Thanks!
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterControlLogic : MonoBehaviour
{
public enum State { Idle, Walking, Jumping };
public State currentState;
[Header("Movement")]
[SerializeField] float movementSpeed = 10f;
[Header("Jumping")]
public float jumpHeight = 7f;
public bool isGrounded =true;
public float gravity = -9.81f;
[Header("Ground")]
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Rigidbody rb;
public Vector3 movement;
// Start is called before the first frame update
void Start()
{
rb = this.GetComponent<Rigidbody>();
currentState = State.Idle;
}
// Update is called once per frame
void Update()
{
}
void FixedUpdate()
{
if (currentState != State.Jumping)
{
RespondToWalking();
}
if (currentState == State.Jumping && isGrounded)
{
inputJumping();
}
}
void RespondToWalking() {
if (isGrounded == false)
{
print("inair");
currentState = State.Jumping;
}
movement = new Vector3(Input.GetAxis("Horizontal"), 0, 0);
if (Input.GetAxis("Horizontal") > 0f) //if they player move right
{
rb.MovePosition(transform.position + ( movement * movementSpeed * Time.deltaTime));
currentState = State.Walking;
}
if (Input.GetAxis("Horizontal") < 0f) //if they player move left
{
rb.MovePosition(transform.position + (movement * movementSpeed * Time.deltaTime));
currentState = State.Walking;
}
if (Input.GetAxis("Horizontal") == 0f) //if the player isn't moving Idle
{
currentState = State.Idle;
return;
}
}
private void inputJumping()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
{
if (Input.GetButtonDown("Jump") && isGrounded)
{
print("jump");
rb.AddForce(Vector3.up * jumpHeight * -2f * gravity);
isGrounded = false;
currentState = State.Jumping;
}
else
{
return;
}
}
}
void doublejump()
{
}
void OnCollisionEnter(Collision other)
{
isGrounded = true;
}
void OnCollisionExit(Collision other)
{
}
}
Comment
Your answer
Follow this Question
Related Questions
Fix for inconsistent jump height? 1 Answer
Basic MOVE and JUMP script (Jump trouble) 2 Answers
Make character face movement direction 0 Answers
ridgidbody AddForce in direction player is pointed? 1 Answer
Character Cannot Move from its Spot 0 Answers