JustCore
JustCore

Reputation: 67

Rigidbody2D goes through walls

I want to add the ability for the player to pick up boxes and move them around, but when the player picks up a box and touches a wall, it starts to twitch and go through it.

Please tell me how this can be fixed. I'm at a dead end.

Here is a video displaying my problem: https://youtu.be/TGt73ASBYpQ

Some code:

//The point at which an box is attracted    
attractedTo = player.transform.position + (player.lookDirection * player.itemHoldDistance);
//Attraction
transform.position += attractedTo - transform.position;

P.S. Sorry for my bad English

Upvotes: 1

Views: 202

Answers (2)

KiynL
KiynL

Reputation: 4266

In fact, transform.position creates an absolute component and changing it creates point-to-point displacement. transform never considers physics and colliders. Use rigidbody to solve the problem.

private Rigidbody2D rigidbody;
public void Start() => rigidbody = GetComponent<Rigidbody2D>();
rigidbody.MovePosition(attractedTo);

If the problem persists, you must create a condition not to be on the wall.

public LayerMask wallLayer; // define layer field

if (boxCollider.IsTouchingLayers(wallLayer.value)) return; // =

Upvotes: 1

ordancheg
ordancheg

Reputation: 43

You are modifying the position of the held object use the rigidbody functions like AddForce instead.

Upvotes: 2

Related Questions