Hi there,
So in my scene I have two game objects - one is a square and the other is a wall that is located to the right of it.
Upon running the project the square travels to the right along the X-axis using the transform.Translate function. When a raycast that shoots from the side of the square hits the wall the square is meant to travel the value that is stored in “hit.distance”. Once this happens the square will stop and rest flush against the wall.
However when I run the project the code only works when there is a Kinematic Rigidbody2D attached to the square. Whereas if I removed the Rigidbody I get very unpredictable behaviour when the raycast hits the wall. I don’t understand why this is? Why is a Kinematic Rigidbody2D needed for the code to work in a predictable manner?
Here is a video demonstrating how running the code with and without the Rigidbody2D affects the wall:
And here is the code that is attached to the square:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player2 : MonoBehaviour
{
public Vector2 botRight;
private BoxCollider2D _col2D;
public LayerMask _whatIsWall;
public float force = 0.015f;
// Start is called before the first frame update
void Start()
{
_col2D = GetComponent<BoxCollider2D>();
}
// Update is called once per frame
void Update()
{
botRight = new Vector2(_col2D.bounds.max.x,_col2D.bounds.min.y);
RaycastHit2D hit = Physics2D.Raycast(botRight,Vector2.right,1f,_whatIsWall);
Debug.DrawRay(botRight,Vector2.right * 1f,Color.red);
if(hit){
transform.Translate(hit.distance,0,0);
}else{
transform.Translate(force,0,0);
}
}
}
Any helpful information would be appreciated.
Kind regards