Hello,
My 2d platformer character keeps on getting stuck on the walls while in midair. I tried to solve this by setting player velocity to zero upon a sphere cast hitting the wall. However I am new to ray casting and I can’t seem to be able to get the sphere cast to return true.
I have a game object called frontSide that I draw a sphere cast from the transform.position of my player. If anyone could help me figure out why my sphere cast always returns false that would be greatly appreciated.
Code:`using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public bool facingRight = true;
public bool jump = false;
public float horizVel = 0f;
static Vector3 mirrorX = new Vector3(-1,1,1);
public float moveForce = 300f;
public float maxSpeed = 10f;
public float jumpForce = 1000f;
private Animator animator;
private bool grounded = false;
private Transform groundCheck;
private Transform frontSide;
private bool sideCheckLeft;
private bool sideCheckRight;
private RaycastHit hitL;
private RaycastHit hitR;
// Use this for initialization
void Awake () {
animator = GetComponent<Animator>();
groundCheck = transform.Find ("groundCheck");
frontSide = transform.Find ("frontSide");
}
// Update is called once per frame
void Update () {
grounded = Physics2D.Linecast (transform.position, groundCheck.position, 1 << LayerMask.NameToLayer ("ground"));
sideCheckLeft = Physics.SphereCast (transform.position, 2.0f , frontSide.position, out hitL, 100, 1 << LayerMask.NameToLayer ("ground"));
//sideCheckRight = Physics.SphereCast (transform.position, 2.0f, Vector3.right, out hitR, 2, 1 << LayerMask.NameToLayer ("ground"));
if (Input.GetButtonDown ("Jump") && grounded)
jump = true;
print (sideCheckLeft);
if (sideCheckLeft)
// rigidbody2D.velocity.x = 0f;
print ("hit");
Debug.DrawLine(transform.position, frontSide.position, Color.red);
}
void FixedUpdate (){
float h = Input.GetAxis ("Horizontal");
// animator.SetFloat (“Speed”, Mathf.Abs (h));
horizVel = Mathf.Clamp(h*(moveForce/rigidbody2D.mass)*Time.deltaTime, -maxSpeed, maxSpeed);
Vector3 vel = rigidbody2D.velocity;
vel.x = horizVel;
rigidbody2D.velocity = vel;
if ( (h<-0.01f && facingRight) || (h>0.01f && !facingRight) ){
transform.localScale = Vector3.Scale(transform.localScale, mirrorX);
facingRight = !facingRight;
}
if(jump)
rigidbody2D.AddForce(new Vector2(0f, jumpForce));
jump = false;
}
void Flip()
{
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
facingRight = !facingRight;
}
}`
This is a picture of my setup: Imgur: The magic of the Internet