Hi,
I’m working on mario like game, and I have a problem, I want to prevent player from multi jumping. User will be allowed to jump, only when he is touching ground, not walls and enemys.
My idea was to create Triggers with Tag “Ground” and add this to objects, but it’s taking forever, since I’m adding more and more objects.
Here is my code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
public bool isOnGorund;
...
if (Input.GetKeyDown(KeyCode.Space))
{
if (isOnGorund)
{
RB.AddForce(Vector3.up * jumpPower * characterBoostJump * Time.deltaTime, ForceMode.Impulse);
isOnGorund = false;
}
}
...
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Ground"))
{
isOnGorund = true;
}
}
Those dots are just parts that I skipped in sharing, cuz they don’t have anything important with my problem, if someone wants to see whole code just write.
Attachment: Image with my idea(Black = Ground, Green = Collision, Blue = Player)
Solving this on the character side of things is much less labor-intensive than having to add that metadata for every single surface in your game, not to mention less error-prone. It’s also fairly easy:
When using OnCollisionEnter, the collision parameter that is sent to the function includes .contacts, an array of information about all the points where a collision happened (often just one). The contact includes the position that the collision occurred, as well as the surface normal of the thing you hit. You can either A) check the contact point’s position against the Y position of the character and see if it’s lower, which means you’ve hit ground; or B ) compare the contact’s normal to Vector3.up; if the Vector3.Angle between them is small, this means you’ve hit the ground.