Question by
LittleSnipe · May 22, 2020 at 06:27 PM ·
c#unity 2d
bool not working right on collision
I have this script and in - void(OnTriggerStay2D) i'm trying to make that the player can't jump unless he is on the ground (i called it "Ground_above"). basically if you collide with the ground onGround = true and if you not onGround = false but for some reason onGround is always false, why and how do i fix it?
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using UnityEngine;
public class movement : MonoBehaviour
{
public Rigidbody2D rb;
public float vel = 7.5f;
public float jump_vel = 5f;
public bool onGround = true;
void Start()
{
rb = this.GetComponent<Rigidbody2D>();
}
void Update()
{
Debug.Log(onGround);
}
void OnTriggerStay2D(Collider2D other)
{
Debug.Log(other.GetComponent<Collider>().name);
if (other.GetComponent<Collider>().name == "Ground_above")
{
onGround = true;
}
else
{
onGround = false;
}
}
void FixedUpdate()
{
Vector2 velocity = rb.velocity;
velocity.x = vel;
if (Input.GetKeyDown("space") && onGround == true)
{
velocity.y += jump_vel;
}
rb.velocity = velocity;
}
}
Comment
Your answer
Follow this Question
Related Questions
Highscore not working 0 Answers
Instanciated objects can only be seen if they were instanciated while looking to the left. 0 Answers
RayCast 2d change start position ? 0 Answers
Calculate BoxCollider2D based on the actual player sprite 2 Answers
Unable to save the captured photo in hololens app. 0 Answers