Hi!
I’m trying to make a simple 2D platformer, but I’m stuck on ground collision. I used two Raycasts to check if there’s something with the tag “Ground” below my player, so I can check for the two outer parts of my player.
I did the checking within an if statement, where we would check for groundHit || groundHit2. In this case it only checks for groundHit. If I put if(groundHit2 || groundHit) it will only check for groundHit2. Have been stuck on this a little while so would love to hear a solution to this problem. ![]()
Here’s my code:
using UnityEngine;
using System.Collections;
public class playerMove : MonoBehaviour {
private float moveSpeed;
private Rigidbody2D playerRB;
private float jumpPower;
private Vector2 jumpVector;
private bool isGrounded;
private Vector2 raycastPosition;
private Vector2 raycastPosition2;
private Vector3 raycastTest;
private Vector3 raycastTest2;
// Use this for initialization
void Start () {
playerRB = GetComponent<Rigidbody2D> ();
moveSpeed = 5.0f;
jumpPower = 300.0f;
jumpVector = new Vector2 (0, jumpPower);
}
// Update is called once per frame
void FixedUpdate () {
//Moving left and right
transform.Translate (Input.GetAxis("Horizontal")*moveSpeed*Time.deltaTime, 0, 0);
//Checking if ground below
raycastPosition = new Vector2(transform.position.x - 0.37f, transform.position.y - 0.505f);
raycastPosition2 = new Vector2(transform.position.x + 0.37f, transform.position.y - 0.505f);
RaycastHit2D groundHit = Physics2D.Raycast (raycastPosition, Vector2.down, 0.020f);
RaycastHit2D groundHit2 = Physics2D.Raycast (raycastPosition2, Vector2.down, 0.020f);
raycastTest = new Vector3 (transform.position.x - 0.37f, transform.position.y - 0.505f, 0);
raycastTest2 = new Vector3 (transform.position.x + 0.37f, transform.position.y - 0.505f, 0);
Debug.DrawRay (raycastTest, Vector3.down);
Debug.DrawRay (raycastTest2, Vector3.down);
if (groundHit.collider.gameObject.tag == "Ground" || groundHit2.collider.gameObject.tag == "Ground") {
isGrounded = true;
}
//jumping
if (Input.GetKeyDown (KeyCode.Space) && isGrounded)
{
playerRB.AddForce (jumpVector);
}
Debug.Log (isGrounded);
}
}