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());
}
}