- Home /
RigidBody2D mouse going through Collider ,Rigidbody2D move with mouse
I am in the progress of making a 2D game where the player can shoot out an orb that can be controlled via the mouse. Currently, the prefab of the orb has a rigidbody2D and a circle collider 2D. The tile collider on the level seems to be able to stop the prefab at first, however, when I drag my mouse at a faster speed it punches straight through. I have been told that I need to not use transform and I edited my code but to no use. Any suggestions?
public class Memory : MonoBehaviour
{
private Vector3 mousePosition;
public float moveSpeed = 0.1f;
private Rigidbody2D rb2D;
// Use this for initialization
void Start () {
rb2D = GetComponent<Rigidbody2D>();
}
void FixedUpdate () {
mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
rb2D.position = Vector2.Lerp(rb2D.position, mousePosition, moveSpeed);
}
}
Answer by VeryAnnoyingCat · Jan 28, 2021 at 05:58 PM
First of all set the rigidbody collision detection of the orb to continuous. Then use this code: Hopefully you know how to use layer masks.
private Vector3 mousePosition;
public float moveSpeed = 0.1f;
public float maxSpeed;
private Rigidbody2D rb2D;
private Collider2D c2D;
public LayerMask collidable; // list of things that are collidable with. !!!Set the orb on its separate layer and unckeck it it the layermask!!!
private RaycastHit2D collidingCheck;
// Use this for initialization
void Start()
{
rb2D = GetComponent<Rigidbody2D>();
c2D = GetComponent<Collider2D>();
}
void Update()
{
mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
collidingCheck = Physics2D.Raycast(transform.position, ((Vector2)(mousePosition - transform.position)).normalized, ((Vector2)(mousePosition - transform.position)).magnitude, collidable);
//checks if anything is between orb and cursor
if (c2D.IsTouchingLayers(collidable) == false || collidingCheck.collider == null) //checks if orb is touching something or if something is between it. Does not allow movement if both.
{
rb2D.position = Vector2.Lerp(rb2D.position, mousePosition, moveSpeed);
}
}
By the way, this will still not work at high speeds so set move speed to a low value.
Your answer
Follow this Question
Related Questions
CircleCollider2D vs PolygonCollider2D: which collision solving is less expensive? 1 Answer
Per-Sorting Layer Collision 1 Answer
[2Dplatformer][Problem] When the player closes to the enemy, the enemy pass through the colliders 0 Answers
Side Collision on "One Way" platform? 2 Answers
Player Gets Stuck On TilemapCollider2D 0 Answers