I am trying to get this jump/movement system and the bool for a ground check is not changing. When I try the code the value of the bool is its starting value. Here is my code. The code is c# and the engine I am using is unity.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MOVEMENT : MonoBehaviour
{
public float playerJumpHeight;
public GameObject player;
public float speed;
public float PlayerXPosition;
public bool isgrounded = false;
public GameObject data_to;
void fixedupdate()
{
PlayerXPosition = player.transform.position.x;
}
void OnCollisionEnter(Collision theCollision)
{
if (theCollision.gameObject.name == "floor")
{
isgrounded = true;
transform.Translate(0,0,1);
}
if (theCollision.gameObject.name == "Height_Check")
{
isgrounded = false;
transform.Translate(0,0,0);
}
}
//consider when the character is jumping .. it will exit collision.
void OnCollisionExit(Collision theCollision)
{
if (theCollision.gameObject.name == "floor")
{
isgrounded = false;
}
}
void Update()
{
Rigidbody2D rb = GetComponent<Rigidbody2D>();
if (Input.GetKeyDown(KeyCode.W) && isgrounded == true) {
rb.AddForce(transform.up * speed);
}
if (Input.GetKey(KeyCode.A))
rb.AddForce(Vector2.left);
if (Input.GetKey(KeyCode.D))
rb.AddForce(Vector2.right);
}
}
CodePudding user response:
If your game is 2D, you must use OnCollisionEnter/Exit
2D.
void OnCollisionEnter2D(Collision theCollision)
{
if (theCollision.gameObject.name == "floor")
{
isgrounded = true;
transform.Translate(0, 0, 1);
}
// ...
}