I am making a stickman parkour/plat former type game. I want my player to be able to throw objects. However, when I throw the object it sometimes gets stuck in mid air. It behaves like there is a collider below it, however there is none. I set the RigidBody2D colliion detection to continous. No other object is under it. Here is a picture:
Here are the settings on the box/crate in the photo:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HoldObjectScript : MonoBehaviour
{
// Arm that will hold object
public Rigidbody2D arm;
// Player root object
public GameObject root;
// Point where to connect the object
public Transform connectPoint;
// Joint used to connect objects
private HingeJoint2D currentJoint;
// Settings
public float throwStrength;
public void TryHoldObject(GameObject obj)
{
if (Input.GetKeyDown(KeyCode.H))
{
// We get the joint that will be used to connect the object
HingeJoint2D joint = obj.GetComponent<HingeJoint2D>();
// We connect the object to arm
joint.connectedBody = arm;
joint.connectedAnchor = connectPoint.localPosition;
// We disable all collisions between object and player
DisableCollisions(obj.GetComponent<Collider2D>());
// Enable the joint
joint.enabled = true;
// Remember the joint
currentJoint = joint;
}
}
public void StopHolding()
{
EnableCollisions();
currentJoint.enabled = false;
}
void DisableCollisions(Collider2D collider)
{
Collider2D[] colliders = root.GetComponentsInChildren<Collider2D>();
for (int i = 0; i < colliders.Length; i++)
{
Physics2D.IgnoreCollision(colliders[i], collider);
}
}
void EnableCollisions()
{
Collider2D[] colliders = root.GetComponentsInChildren<Collider2D>();
Collider2D collider = currentJoint.GetComponentInParent<Collider2D>();
for (int i = 0; i < colliders.Length; i++)
{
Physics2D.IgnoreCollision(colliders[i], collider, false);
}
}
public void ThrowObject(Vector2 direction)
{
Rigidbody2D objectRb = currentJoint.GetComponentInParent<Rigidbody2D>();
StopHolding();
objectRb.velocity = direction * throwStrength;
}
}
I basically receive a direction and apply a force to it.