- Home /
2D Raycasting to check if grounded not working
I'm currently working on optimizing an old game project of mine, completely redoing the controls, improving graphics, etc. Originally, I had been using an excessive amount of colliders to check if the player was grounded(to avoid infinite jumping) but during optimization, I decided to use raycasts. I can't figure out why my (C#) code isn't working, and even though I saw many different questions with answers on the topic, they weren't very helpful to me. Player Script with Raycasting Code: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PplayerScript : MonoBehaviour
{
//Variables
public int movementSpeed;
public int jumpHeight;
public Rigidbody2D rb;
public SpriteRenderer SpriteRenderer;
public bool canJump;
public RaycastHit hit;
void Update()
{
//Player controls
if (Input.GetKey("a"))
{
transform.Translate(Vector3.left * Time.deltaTime * movementSpeed);
SpriteRenderer.flipX=true;
}
if (Input.GetKey("d"))
{
transform.Translate(Vector3.right * Time.deltaTime * movementSpeed);
SpriteRenderer.flipX = false;
}
//Raycasting
Vector2 fwd = transform.TransformDirection(Vector2.up);
Debug.DrawRay(transform.position, fwd * -0.55f, Color.red);
if (Physics.Raycast(transform.position, fwd * -0.55f) && hit.transform.gameObject.tag == "Ground")
{
Debug.DrawRay(transform.position, fwd * -0.55f, Color.green);
Debug.Log("lel");
canJump = true;
}
else
{
Debug.DrawRay(transform.position, fwd * -0.55f, Color.blue);
canJump = false;
}
//Checking canJump
if (Input.GetKey("space") && canJump==true)
{
rb.AddForce(Vector2.up * jumpHeight, ForceMode2D.Impulse);
}
}
}
Any ideas? Thanks, EpicCrownKing
Answer by I_Am_Err00r · Jul 23, 2019 at 05:36 PM
I want to try and help, but can you tell me where it gives you errors? What Debug.Logs are coming back as true or giving you the correct answers?
I don't have a compiler, am just typing this at my call center job right now, so I can't test, but I do see you don't have any variables defining the raycast sizes, hardcoding those values probably isn't the best solution, and maybe making something public and setting it in the inspector might be the best way to go until you find a more elegant solution that can define it exactly every time.
This video on youtube has a 2D raycasting tutorial that you should check out.
Sorry I couldn't give you the golden solution, but raycasting has to be very precise for it to work all the time, and if you don't have it setup correctly, it will give you a lot of headaches.
Well, thanks for the help! I'm not actually getting any errors, the player simply isn't jumping. I am debugging the raycast, which always shows up as blue. I'll try assigning the raycast size to a singular variable within the code. I'll check out that video and get back to ya. -EpicCrown$$anonymous$$ing