How To Animate A Pickup In Unity

Are y'all looking for information or an example of how to implement picking up items in Unity?
Look no further! In this postal service, you lot will find a simple solution for that.
We will make the first-person character with motility and grabbing scripts, and we will make another i for objects that we would like to pick upwardly.
Let's see how we can do that! 🤓
Character 🚶♂️
First of all, we will need a grapheme that tin move around in the scene.
Nosotros volition build that character from a capsule, and we will movement our master photographic camera to be a kid of this object.

Next, we take to create a movement script. Nosotros will use a CharacterController component with our simple motility script.
using UnityEngine; /// <summary> /// Simple player motion. /// </summary> [RequireComponent(typeof(CharacterController))] public class SimplePlayerMovement : MonoBehaviour { [Header("Character")] // Reference to the character controller [SerializeField] private CharacterController graphic symbol; // Graphic symbol movement speed. [SerializeField] individual bladder moveSpeed = 4; [Header("Camera")] // Reference to the graphic symbol camera. [SerializeField] private Camera characterCamera; // Camera movement speed. [SerializeField] private float camSpeed = forty; /// <summary> /// Method called at the start. /// </summary> private void First() { // Lock and hide cursor Cursor.lockState = CursorLockMode.Locked; Cursor.visible = imitation; } /// <summary> /// Method chosen every frame. /// </summary> private void Update() { // Get histrion input for character movement var v = Input.GetAxis("Vertical"); var h = Input.GetAxis("Horizontal"); // Create movement vector and rotate it var move = new Vector3(h, 0, v); move = character.transform.rotation * motion; // If length of move vector is bigger than 1, normalize it. if (motility.magnitude > i) move = move.normalized; // Motion character character.SimpleMove(movement * moveSpeed); // Go histrion mouse input for camera and character rotation var mx = Input.GetAxisRaw("Mouse 10"); var my = Input.GetAxisRaw("Mouse Y"); // Rotate character with mouse X value grapheme.transform.Rotate(Vector3.up, mx * camSpeed); // Go camera rotation on X axis var currentRotationX = characterCamera.transform.localEulerAngles.ten; currentRotationX += my * camSpeed; // Limiting camera movement to (-threescore) - (sixty) degrees on X axis. if (currentRotationX < 180) { currentRotationX = Mathf.Min(currentRotationX, threescore); } else if (currentRotationX > 180) { currentRotationX = Mathf.Max(currentRotationX, 300); } // Assign new photographic camera rotation characterCamera.transform.localEulerAngles = new Vector3(currentRotationX, 0, 0); } }
With this script ready, at present we can attach it to the player object and assign references.

Grabbing organization 🤏
Creating a grabbing system is not that hard to begin with. We basically need only two classes. Ane, with nosotros will attach to the player, and the 2d one, which we volition adhere to the pickable objects.
But before nosotros can implement them, we need to create a slot where nosotros will hold our picked objects. You just need to add an empty object (or cube) under the player photographic camera then nosotros can see that we have something in our "hand".


Making object pickable 👌
Now it's time to create new classes for our system! Permit'due south offset with PickableItem first, equally it will be a really brusk script.
using UnityEngine; /// <summary> /// Attach this form to brand object pickable. /// </summary> [RequireComponent(typeof(Rigidbody))] public class PickableItem : MonoBehaviour { // Reference to the rigidbody private Rigidbody rb; public Rigidbody Rb => rb; /// <summary> /// Method called on initialization. /// </summary> private void Awake() { // Get reference to the rigidbody rb = GetComponent<Rigidbody>(); } }
With this class, we tin can make object pickable. I would recommend creating a "parent" game object with this component, as information technology will be easier to rotate and position it in a slot.


At present, yous only need to attach our component to the parent and a Mesh Collider to the model itself with " Convex " option enabled.


Let's grab some items! 🙌
The 2d script of our organisation will be attached to the player and will be responsible for handling picking upwardly items and dropping them onto the floor.
Allow's create SimpleGrabSystem class!
using UnityEngine; /// <summary> /// Simple instance of Grabbing system. /// </summary> public class SimpleGrabSystem : MonoBehaviour { // Reference to the character camera. [SerializeField] private Camera characterCamera; // Reference to the slot for holding picked item. [SerializeField] individual Transform slot; // Reference to the currently held item. individual PickableItem pickedItem; /// <summary> /// Method called very frame. /// </summary> private void Update() { // Execute logic only on button pressed if (Input.GetButtonDown("Fire1")) { // Check if role player picked some item already if (pickedItem) { // If aye, drop picked particular DropItem(pickedItem); } else { // If no, try to pick detail in front end of the player // Create ray from center of the screen var ray = characterCamera.ViewportPointToRay(Vector3.i * 0.5f); RaycastHit hitting; // Shot ray to find object to selection if (Physics.Raycast(ray, out hit, i.5f)) { // Check if object is pickable var pickable = hit.transform.GetComponent<PickableItem>(); // If object has PickableItem course if (pickable) { // Pick it PickItem(pickable); } } } } } /// <summary> /// Method for picking up item. /// </summary> /// <param name="particular">Item.</param> private void PickItem(PickableItem detail) { // Assign reference pickedItem = particular; // Disable rigidbody and reset velocities item.Rb.isKinematic = truthful; item.Rb.velocity = Vector3.nada; item.Rb.angularVelocity = Vector3.nothing; // Gear up Slot as a parent item.transform.SetParent(slot); // Reset position and rotation item.transform.localPosition = Vector3.zilch; item.transform.localEulerAngles = Vector3.zero; } /// <summary> /// Method for dropping particular. /// </summary> /// <param proper noun="item">Item.</param> private void DropItem(PickableItem item) { // Remove reference pickedItem = nix; // Remove parent item.transform.SetParent(null); // Enable rigidbody item.Rb.isKinematic = false; // Add force to throw item a fiddling bit detail.Rb.AddForce(detail.transform.frontward * ii, ForceMode.VelocityChange); } }
Great! The but affair left is to attach this grade to the player!

The upshot 🏆
So allow'south finally exam that thing!

And as you can see, nosotros created a elementary solution for picking and dropping items in Unity.
If you found that helpful, share what project you are working on in the comment section below! I would love to know! 😍
You lot can check the whole project at my public repository. 🔗
And if you are interested in getting emails when I release a new postal service, sign up for the newsletter!
Hope to see you side by side fourth dimension! 🤓
Source: https://www.patrykgalach.com/2020/03/16/pick-up-items-in-unity/
Posted by: petersonquilichich.blogspot.com
0 Response to "How To Animate A Pickup In Unity"
Post a Comment