So I have made my script work in my player jumps when he’s hitting any object tagged “Ground”. But in trying to clean up my code I’m having a hard time being able to call OnCollisionEnter.
This code works great
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class jumpgrounded : MonoBehaviour
{
public float speed = 4.5f;
private Rigidbody rb;
public float jumpForce = 9;
public bool cubeIsOnTheGround = true;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
PlayerMove();
}
void PlayerMove()
{
float leftRight = Input.GetAxis("Horizontal");
float forwardBack = Input.GetAxis("Vertical");
Vector3 movePlayer = new Vector3(leftRight, 0, forwardBack) * speed * Time.deltaTime;
transform.Translate(movePlayer, Space.Self);
if (Input.GetButtonDown("Jump")&& cubeIsOnTheGround)
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
cubeIsOnTheGround = false;
}
}
private void OnCollisionEnter(Collision collision)
{
Debug.Log("Entered");
if (collision.gameObject.tag==("Ground"))
{
cubeIsOnTheGround = true;
}
}
}
But I would like to clean the code up my code and to call a jump method and also use OnCollisionEnter But when I do it only jumps once? So I guess you cannot call OnCollisionEnter as a method??
public class jumpgroundmethod : MonoBehaviour
{
public float speed = 4.5f;
private Rigidbody rb;
public float jumpForce = 9;
public bool cubeIsOnTheGround = true;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
PlayerMove();
Jumping();
}
void PlayerMove()
{
float leftRight = Input.GetAxis("Horizontal");
float forwardBack = Input.GetAxis("Vertical");
Vector3 movePlayer = new Vector3(leftRight, 0, forwardBack) * speed * Time.deltaTime;
transform.Translate(movePlayer, Space.Self);
}
void Jumping()
{
if (Input.GetButtonDown("Jump") && cubeIsOnTheGround)
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
cubeIsOnTheGround = false;
}
}
void OnCollisionEnter(Collision collision)
{
Debug.Log("Entered");
if (collision.gameObject.tag == ("Ground"))
{
cubeIsOnTheGround = true;
}
}
}