Hey, I’m really sorry if this have been answered before, but I tried looking everywhere and I couldn’t really find my solution. (I should also mention I’m extremely new to this, I tried looking through the manual, but I couldn’t quite find what I did wrong )
So I’m working on a 2D game where there is a character (a UI image) that’s supposed to not walk into walls (also a UI image).
Here’s the code for the character:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour
{
public float speed;
void Update()
{
float v = Input.GetAxisRaw("Vertical");
float h = Input.GetAxisRaw("Horizontal");
Vector3 direction = new Vector3(h, v, 0f).normalized;
transform.Translate(direction * speed * Time.deltaTime);
}
}
(the speed is set to 80 if that matters)
The player has a circle collider 2d and a rigidbody 2d and the wall has a polygon collider 2d and a rigidbody2d (I had heard that technically a rigidbody wouldn’t be necessary if the player has one already, but for some reason it wouldn’t work if the wall didn’t have any). They don’t have any materials attached to them.
So what’s the problem? Well, my player does seem to know that the walls are walls, and it slows down as it comes in collision with the wall, but it can still walk through the wall if you keep pressing. I would like for the wall to be completely impenetrable, but I can’t seem to make that work
Things I’ve tried:
-Making sure that none of the box collider have IsTrigger checked (they don’t).
-Using OnCollisionEnter2D to bring the speed to 0 once they come into collision (the speed does go to 0, but then it stays that way so the player can’t move anymore, which is not what I want).
What can I do to make the walls completely impenetrable? Thank you so much in advance and I’m sorry if this is long, I just wanted to make sure this was detailed (I can add screenshots of the components if necessary, there’s just an image limit here haha).