- Home /
How to make drag and throw (2D)
Hi, I need to do drag and throw and I know there are lots of identical questions and generally the answer is SpringJoint or its types.
I tried joints but Im not satisfied with them, they stretch too much and/or circle around the mouse. I haven't found any way to fix this anywhere on internet.
So I have 2 questions:
How do Imake trully rigid spring joint?
And if I can't, what should I use for drag and throw?
Answer by metalted · Dec 14, 2021 at 01:20 PM
I never really tried making a drag and throw kind of mechanic, so I thought it would be a nice challenge. I didn't use any joints, just the rigidbody and the mouse input. It's a bit of a 10-min code jam, so embrace the jank I guess. What I did was use a raycast to detect the object and a mouse button to grab. While holding the object, store the previous' frame position and the current frames position. When releasing the mouse button use the two positions to calculate the drag direction and the distance (distance per frame = speed) and add some force to the rigidbody. Things I noticed already is that you might want to clamp the distance value so it doesn't fly off. Not saying this is the best or only solution, but it is a solution. Hope it helps you out.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseDragThrow : MonoBehaviour
{
public GameObject currentlyDraggedObject = null;
private float savedZPosition = 0;
public Camera cam;
private Vector3 previousDragPosition;
private Vector3 currentDragPosition;
public void Update()
{
RaycastHit hit;
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
Vector2 mousePosition = Input.mousePosition;
if(Input.GetMouseButtonDown(0))
{
if(Physics.Raycast(ray, out hit))
{
if(hit.collider.gameObject.tag == "Draggable")
{
currentlyDraggedObject = hit.collider.gameObject;
savedZPosition = Mathf.Abs(cam.transform.position.z - currentlyDraggedObject.transform.position.z);
currentlyDraggedObject.GetComponent<Rigidbody>().isKinematic = true;
currentDragPosition = currentlyDraggedObject.transform.position;
}
}
}
if(currentlyDraggedObject != null)
{
currentlyDraggedObject.transform.position = cam.ScreenToWorldPoint(new Vector3(mousePosition.x, mousePosition.y, savedZPosition));
previousDragPosition = currentDragPosition;
currentDragPosition = currentlyDraggedObject.transform.position;
if(Input.GetMouseButtonUp(0))
{
Vector3 direction = currentDragPosition - previousDragPosition;
float distance = Vector3.Distance(previousDragPosition, currentDragPosition);
currentlyDraggedObject.GetComponent<Rigidbody>().isKinematic = false;
currentlyDraggedObject.GetComponent<Rigidbody>().AddForce(direction * distance * 10f, ForceMode.Impulse);
currentlyDraggedObject = null;
}
}
}
}