I am trying to make a slingshot mechanic very much like angry birds in my game. I only want a specific object to be dragged, but I believe the onTriggerEnter function is not working. I’m not sure why, the code seems to all make sense to me. Any thoughts?
private bool draggingItem = false;
private GameObject draggedObject;
private Vector2 touchOffset;
public Rigidbody2D rb;
void start()
{
//
}
void Update()
{
}
void OnTriggerEnter(Collider other)
{
if (HasInput)
{
if (other.gameObject.tag == "Draggable")
{
DragOrPickUp();
}
}
else
{
if (draggingItem)
DropItem();
}
}
Vector2 CurrentTouchPosition
{
get
{
Vector2 inputPos;
inputPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
return inputPos;
}
}
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
private void DragOrPickUp()
{
var inputPosition = CurrentTouchPosition;
if (draggingItem)
{
rb.isKinematic = true;
draggedObject.transform.position = inputPosition + touchOffset;
}
else
{
RaycastHit2D[] touches = Physics2D.RaycastAll(inputPosition, inputPosition, 0.5f);
if (touches.Length > 0)
{
rb.isKinematic = true;
var hit = touches[0];
if (hit.transform != null)
{
draggingItem = true;
draggedObject = hit.transform.gameObject;
touchOffset = (Vector2)hit.transform.position - inputPosition;
draggedObject.transform.localScale = new Vector3(1.2f, 1.2f, 1.2f);
}
}
}
}
private bool HasInput
{
get
{
// returns true if either the mouse button is down or at least one touch is felt on the screen
return Input.GetMouseButton(0);
}
}
void DropItem()
{
rb.isKinematic = false;
draggingItem = false;
draggedObject.transform.localScale = new Vector3(1f, 1f, 1f);
}
}