- Home /
can i 2d wall collision without major changes?
im in the very early stages of making a 2d RPG and i want my 2d player(only a sprite but has been given a 2d box collider and 2d rigidbody) to stop moving once he touches anything on he touches, i havent used unity in this scope in 4 years and dont retain the knowledge on it that i had, i want the following code to incorperate collision with as little change to current formula as possible:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAI : MonoBehaviour
{
private int Playerlevel;
private float speed = 0.1f;
private Vector2 playerpos;
private Rigidbody2D player_rb;
// Start is called before the first frame update
void Start()
{
//player_rb = GetComponent<Rigidbody2D>();
playerpos = transform.position;
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.W)) playerpos.y += speed; // y++
if (Input.GetKey(KeyCode.A)) playerpos.x -= speed; // x--
if (Input.GetKey(KeyCode.S)) playerpos.y -= speed; // y--
if (Input.GetKey(KeyCode.D)) playerpos.x += speed; // x++
transform.position = playerpos;
}
void OnCollisionEnter2D(Collision2D collision)
{
}
void OnGUI()
{
GUI.Label(new Rect(0, 45, 200, 50), playerpos.x.ToString() + ", " + playerpos.y.ToString());
}
}
Answer by RodrigoAbreu · Feb 07, 2021 at 06:34 AM
Hey @Advigames, here is how you should do it.
using UnityEngine;
public class PlayerAI : MonoBehaviour
{
private int Playerlevel;
private float speed = 100f;
private Vector2 playerpos;
private Rigidbody2D player_rb;
void Start()
{
player_rb = GetComponent<Rigidbody2D>();
}
public void FixedUpdate()
{
player_rb.velocity = new Vector3(Input.GetAxisRaw("Horizontal") * speed * Time.fixedDeltaTime,
Input.GetAxisRaw("Vertical") * speed * Time.fixedDeltaTime);
}
void OnCollisionEnter2D(Collision2D collision)
{
player_rb.velocity = Vector2.zero;
}
void OnGUI()
{
GUI.Label(new Rect(0, 45, 200, 50), playerpos.x.ToString() + ", " + playerpos.y.ToString());
}
}
This is the Player Setup:
For the wall you just need to add a BoxCollider2D
Remember to lock your rotation constraints Z on your Player's rigidBody2D
Answer by logicandchaos · Feb 06, 2021 at 01:47 PM
if you have a collision box and rb on your character already, you just need to put collision on your walls, no coding needed.
You can also do this:
void OnCollisionEnter2D(Collision2D collision)
{
rb.velocity=Vector2.zero;
}
i tried adding that code and nothing happened, also my objects that i want the player to collide into already have a 3d box collider and 2d rigidbody. do i have to completely rework how the inputs move the player?
@Advigames It will not work, because you're not moving your character with velocity. You need to actually make sure your walls have a collider on them, they won't need a rigidbody. Also make sure all your colliders are not marked as "trigger".
okay, so how do i edit my code so i can move my character with velocity?