Im making a 2D platformer ( I know, very original) and my character moves and jumps around perfectly. My problem is that it keeps moving through walls.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Playermove : MonoBehaviour
{
Animator playeranimator;
Rigidbody2D playerRb;
public float speed = 4f;
bool facingRight;
private bool isGrounded;
public Transform feetpos;
public float checkradius;
public LayerMask whatisground;
public float jumpforce;
private float jumptimecounter;
public float jumptime;
private bool isJumping;
// Start is called before the first frame update
void Start()
{
playeranimator = GetComponent<Animator>();
playerRb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
//get ground
isGrounded = Physics2D.OverlapCircle(feetpos.position, checkradius, whatisground);
//Get input
float movement = Input.GetAxis("Horizontal");
//Move along the x axis
Vector3 playerPosition = transform.position;
playerPosition.x = playerPosition.x + movement*speed *Time.deltaTime;
transform.position = playerPosition;
//Jump
if(isGrounded == true && Input.GetKeyDown(KeyCode.Space)){
isJumping = true;
jumptimecounter = jumptime;
playerRb.velocity = Vector2.up * jumpforce;
}
if(Input.GetKey(KeyCode.Space) && isJumping){
if(jumptimecounter > 0){
playerRb.velocity = Vector2.up * jumpforce;
jumptimecounter -= Time.deltaTime;
}
else{
isJumping = false;
}
}
if(Input.GetKeyUp(KeyCode.Space)){
isJumping = false;
}
/*
if(Input.GetKey(KeyCode.Space) )
{
playerRb.AddForce(Vector2.up*1f, ForceMode2D.Impulse);
}
*/
//prevent sliding down slopes
if(Input.GetKey(KeyCode.Space) == false || Input.GetAxis("Horizontal") == 0){
playerRb.constraints = RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezeRotation;
}
else{
playerRb.constraints = RigidbodyConstraints2D.FreezeRotation;
}
Flip(movement);
//Change Animation
playeranimator.SetFloat("Speed", speed*0.75f);
playeranimator.SetFloat("Move", Mathf.Abs(movement));
playeranimator.SetBool("Jump", isJumping);
}
void Flip(float m)
{
//Get current direction and compare it to movement direction
if(facingRight && m < 0 || !facingRight && m > 0)
{
//if they are not the same, then flip and change facingdirection
transform.Rotate(new Vector3(0,180,0));
facingRight = !facingRight;
}
}
}
Thats my movement script in its entirety. I wasnt sure how much of it was needed.
I think that this part is whats causing the problem.
I have tried replacing that part with various solutions using rigibodies but that just causes my character to slowly move downwards and not be able to move side to side.
Please help. Thank you.