Well I haven’t posted in a while but here goes:
I am making a simple game where you can grab and throw things, but I don’t know any suitable script for making my grab’n throw system, I want the player to grab anything with a RigidBody
and it’s tag has "holdable"
. It grabs anything that is on the mouse position when E
is pressed, any code?
It feels pretty straight forward to me:
- attach a
FixedJoint
to your player and put a script that casts a ray from the mouse position to the world
- then just get the
RigidBody
of the object that the ray has hit
- and finally replace
FixedJoint.connectedBody
with that RigidBody
.
I will probably update this answer with the code a bit later.
UPD: Something like this:
using UnityEngine;
using UnityEngine.Serialization;
public class ItemPicker : MonoBehaviour
{
private FixedJoint joint;
[SerializeField] private Camera cam;
[SerializeField] private float reach; //max distance at which an item would be picked
private void Start()
{
joint = gameObject.GetComponent<FixedJoint>();
cam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
}
private void FixedUpdate()
{
if (Input.GetKey(KeyCode.E))
{
if (joint.connectedBody is null)
{
RaycastHit hit;
if (Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit, reach))
{
joint.connectedBody = hit.rigidbody;
}
}
else
{
joint.connectedBody = null;
}
}
}
}