I have been messing around with different kinds and so far, I find OnTriggerEnter and OnCollision enter the easiest to use, I did also use Raycasting (and Boxcasting), but I have a problem with trying to figure out how to make a cast that allows me to detect multiple things via Raycasting, but i just can’t figure it out. I managed to detect Ground this way, but I want to use the same boxcast to also detect if an enemy is under me, and then do another action.
Also I wanted to try and check collision in front of the player, and when he goes the other way, the ray does as well, I just have no idea how to make that either. Any help is appreciated!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerController : MonoBehaviour
{
//Main Functions
[SerializeField] private LayerMask platformLayerMask;
public Rigidbody2D rb2D;
public BoxCollider2D bc2D;
private float mvSpeed = 5.5f;
public float jumpMagnitude;
public static bool isAlive = true;
private bool canDoubleJump = false;
//Extra Variables
void Awake() {
rb2D.freezeRotation = true;
rb2D = gameObject.GetComponent<Rigidbody2D>();
bc2D = gameObject.GetComponent<BoxCollider2D>();
}
void FixedUpdate() {
plControl();
}
void plControl() {
if (Input.GetKey(KeyCode.D)) {
rb2D.velocity = new Vector2(mvSpeed, rb2D.velocity.y);
}
else if (Input.GetKey(KeyCode.A)) {
rb2D.velocity = new Vector2(-mvSpeed, rb2D.velocity.y);
} else {
rb2D.velocity = new Vector2(0, rb2D.velocity.y);
}
if (isGrounded() && Input.GetKey(KeyCode.Space)) {
jumpMagnitude = 10.0f;
rb2D.velocity = Vector2.up * jumpMagnitude;
}
}
//Checks if the player is on solid ground by using RaycastHit2D
private bool isGrounded() {
float extraHeightText = 0.05f;
//RaycastHit2D raycastHit = Physics2D.Raycast(bc2D.bounds.center, Vector2.down, bc2D.bounds.extents.y + extraHeightText, platformLayerMask);
RaycastHit2D raycastHit = Physics2D.BoxCast(bc2D.bounds.center, bc2D.bounds.size, 0f, Vector2.down, extraHeightText, platformLayerMask);
return raycastHit.collider != null;
}
}