Hello, I made a character movement script with RigidBody2D, and want to stop the object when it collides with another object. Currently, I can move the character left and right but when I run into the object, I get the message “enter” in the console but my position doesn’t freeze, even though in the RigidBody2D menu it shows that my X and Y positions are frozen. I can still move around.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class rigidmove : MonoBehaviour
{
public bool Disheld = false;
public bool Aisheld = false;
public int distance = 5;
// Start is called before the first frame update
void Start()
{
Rigidbody2D rbdy = gameObject.GetComponent();
}
// Update is called once per frame
void Update()
{
Rigidbody2D rbdy = gameObject.GetComponent<Rigidbody2D>();
if (Input.GetKey(KeyCode.D))
{
rbdy.transform.Translate(distance*Time.deltaTime, 0, 0);
}
if (Input.GetKey(KeyCode.A))
{
rbdy.transform.Translate(-distance * Time.deltaTime, 0, 0);
}
if (Input.GetKey(KeyCode.W))
{
rbdy.transform.Translate(0, distance * Time.deltaTime, 0);
}
if (Input.GetKey(KeyCode.S))
{
rbdy.transform.Translate(0, -distance * Time.deltaTime, 0);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
Rigidbody2D rbdy = gameObject.GetComponent<Rigidbody2D>();
rbdy.constraints = RigidbodyConstraints2D.FreezePosition;
print("enter");
}
private void OnTriggerExit2D(Collider2D collision)
{
Rigidbody2D rbdy = gameObject.GetComponent<Rigidbody2D>();
rbdy.constraints = RigidbodyConstraints2D.None;
}
}