PICKUP & DROP Physics Objects in Unity (Like PORTAL)
Вставка
- Опубліковано 19 сер 2024
- Lets learn how to pickup and drop objects in Unity. Objects with a Rigidbody component attached can be manipulated like the portal style physics game mechanics. The system can easily be modified to only pick up objects with a certain tag or adjust the speed at which objects are moved. Written in C# and all the content can be found on my Patreon below.
🎁 Get OVER 160+ Scripts, Projects and premium content on my PATREON HERE:
➡️bit.ly/SpeedTut...
·························································································
🔥 INSANE UNITY SAVINGS: bit.ly/UnitySa...
🕹️Synty Publisher Mega Sale: bit.ly/SyntyPu...
🕹️SpeedTutor Unity Store: bit.ly/STUnity...
🕹️Unity New Release Discount Sale: prf.hn/l/BdvEmg3
🕹️Unity WELCOME2022 Offer: bit.ly/UnityWe...
🔥 INSANE HUMBLE SAVINGS: bit.ly/HumbleB...
🕹️Humble Tutorial Bundle: bit.ly/Mammoth...
🕹️Unity ART Bundle: bit.ly/UnityHu...
🕹️Unity TOOLS Bundle: bit.ly/UnityIn...
🕹️SFX for Games Bundle: bit.ly/SFX-Mus...
🕹️Learn Programming Games Bundle: bit.ly/LearnPr...
🔥Unity Materials / Files & More:
🕹️CGAxis 400 PBR Material Bundle: bit.ly/CGAxisP...
🕹️Synty Assets: bit.ly/SyntyLo...
🕹️Filebase Assets: filebase.gamed... (Code: SPEEDTUTOR2022 - Sign up for a FREE MONTH)
🔥 UNITY SUBSCRIPTIONS:
🕹️Unity Plus: bit.ly/UnityPl...
🕹️Unity Pro: bit.ly/UnityPr...
·························································································
💰BIG DISCOUNTS on my website, for my UNITY ASSETS:
➡️www.speed-tuto...
💬Join the Community Discord:
➡️ / discord
💝 Make a donation to the channel:
➡️www.paypal.me/s...
·························································································
⬇️ SpeedTutor Puzzle Assets:
➡️Unity Store: bit.ly/STUnity...
➡️My Website Discounts: www.speed-tuto...
⬇️ SpeedTutor Best Selling Assets:
🧩Adventure Puzzle Kit: bit.ly/STAdven...
🗒️ Note & Letter System: bit.ly/STNoteL...
🔍Examine System: bit.ly/STExami...
🔢Keypad System: bit.ly/STKeypa...
⬇️SpeedTutor Model Packs:
➡️Unity Store: bit.ly/STUnity...
➡️My Website Discounts: www.speed-tuto...
My Assets include: Gas Mask, Flashlight, Generator, Themed Key , Padlock, Phone, Chess Puzzle, Lever, Valve Puzzle, Fuse Box & Safe Systems. Cardboard, Debris, Massive Models and more!
························································································
⭐ Connect with me:
💬| Discord: / discord
🐦| Twitter: / speedtutor
📱 | Facebook: / speedtutoruk
🖥 | Website: www.speed-tutor...
·······················································································
#SpeedTutor #Unity #Portal
Grab what you can and make a run for it, with this little tutorial! Also a brand new Unity sale below... ANOTHER ONE!
🔥UNITY SAVINGS: bit.ly/UnitySalesHub
🔥SpeedTutor Unity Store: bit.ly/STUnityStorePuzzlePacks
🔥HUMBLE SAVINGS: bit.ly/HumbleBundleDeals
Perfect tutorial, man!!! Sometimes unity teachers have a hard time explaining code, but you do it perfectly!
I'm glad you think so, my dude! Thanks for watching! :D
i found a better feeling rotation control instead of freezing it altogether was to add a field for both linear and angular drag. That way if you want a more skyrim-ish feel you can let the object dangle from the point you are holding it (I'm also using AddForceAtPosition and storing the point on the collider's surface that you clicked on when picking up the object), or crank up the angular drag to get a more portal feel similar to freezerotation
Awesome, thanks for sharing your ideas, implementations and everything. Really helpful. Good luck with your project! :)
Hey, can you share how you do this?
Love the tutorial. Was able to implement easily and understood all because you talked through it.
I believe adding a Tag for pickupableObjects would be good to add to the PickupObject function.
Awesome, thanks for checking this out! What are you creating?
@@SpeedTutor I’m participating in the GDK Game Jam, it’s my first Game Jam. I making a tower defense in which you can pickup the towers.
Great video! I was using a slightly different implementation of this technique and had a lot of issues. Using the rigidbody "Add Force" method of approach solved many of these. Thank you! :)
You're very welcome! :D
Such a class act man. Great content as usual
Thanks man, I appreciate you coming along to watch. You can add it to your game now. ;)
@@SpeedTutor EXCUSE ME, DID YOU JUST GENDER ASSUME THEM?
@@kinda_history_nerd Haha, I know Dead Broadcast from Discord. He's my man. :)
@@SpeedTutorHe is joking, obviously you are a man we can tell by your voice.
Your tutorials are always a blast thank you so much
I'm glad you enjoy them! :)
I'm having a problem where if you move too fast the object goes through other objects like the walls and floor even when the rb is on continuous. I think the problem lies where you parent the object to the holder so the object is always on the holder no matter what so if you point it through the floor it goes right through. how can I fix this?
Can you solve it now? I am encountering this problem as well.
May is to late to help you but for anyone facing this problem look up to the held object's Rigidbody and certify the Collision Detection is on Continuous and Interpolate = Interpolate, but just be ware this option needs more resources than Discrete so if possible avoid using multiples RB on a complex scene
@@AnkoLive Lol two years too late pal. I gave up and became a mechanic lmao. Thank you for anyone else who finds this useful though!
@@Nesrak LOL, Well, in any case I hope you are doing great on this journey!
Thanks. I used it for my third person game. Works very well
Great to hear it! :D Thanks for coming to watch!
Thanks I've been looking for a pick up mechanic that feels like Half Life or Portal's pick up mechanic
Great to hear it, I hope this helps you out! Let me know how it goes! :)
@@SpeedTutor Yeah it works
You are a literal god, saved our gmejam
Awesome, best of luck with your game jam! :D
Hey! Thanks much this was very helpful and a great explanation!
You're very welcome, Tiffany! :)
Great Tutorial straight to the point
I'm glad you think so! :D
Absolutely astounding!
Utterly remarkable!
Is there a way you can keep the momentum of the object when you let go?
How can you make the throw mechanic like when you turn really fast and then drop the object? btw great tutorial very cool
When you're holding your object, you could use "AddForce" again and push it in a direction, with a high threshold! :)
Bless you genius man
Thanks man, love the name! :P
also with this I noticed that small objects phase through walls when held and moved and the items seem to lose their momentum when dropped so you cant 'throw' things@@SpeedTutor
thx for this video c:
You're very welcome, thanks for watching! :)
this video really helped me a lot , but now I'm facing another issue that these boxes which I'm carrying can pass through from the wall !
to fix this issue I placed a script on the Boxes where I'm using "OnTriggerEnter()" if collided with wall then "touch = true" but I don't know why it's not working :(
thank you so so much!
You're very welcome, thanks for watching! :)
Hi! I have a problem: i can grab objects but i can't drop them down, it's like it doesn't recognize when i'm clicking again to drop it.
EDIT: SOLVED! My error was adding the "else" of line 28 right below the "if (Physics.Raycast..." of the line line 22, instead of right below the "if (heldObj...)" of the line 20, so the condition was never being met 👍🏻
Awesome, good job on fixing it! :)
this is great but how would I change it to E instead of left mouse button and have it make a sound when you pick something up.
Use KeyCode.E rathern than the mouse click :) - I do also have tutorials about playing sounds on triggers which might help you too. As you can adapt the code!
@@SpeedTutor ok thanks
Hey is there any other method pickup and drop instead using mouse inputs, something like using colliders, if thats possible could you please help with it.
Thankyou
Hey, everything works well, but whenever I pickup the cube i fly with it
I'm not sure what to suggest, as soon as you pick it up?
@@SpeedTutor Hey thanks for replying, it was actually a problrm with the mini fps controller
I changed it to starter Asset Controller and its all good now thank you
Great job on that, haha. Thanks for letting me know! :)
Nothing's being picked up at all. It knows that I clicked on the object but it's not teleporting to the Hold Area. It's for a Third Person controller.
Is there something I’m missing?
Is there any way this could allow door opening mechanics?
Hi please how can we do it with a mixamo character with a pickup animation script
I'll definitely add this to my list :)
that script is working very well but there's a small problem, which is when I hold the rigidbody it seem like it didn't have a collider, it goes through all wall.
Yeah you've got to add a collider to the box too in order for it to work
i did this with unity's default first person template and it didn't work at all, I'm not getting any errors and my code looks right but i cant pick anything up. did anyone else have this problem and were able to fix it? or should i just make my own first person camera and not use the template?
Which template? Why not try the one from the Standard assets? :)
I don't know why my object orbits the grabpoint :/// it doesn't stop like yours does.... any help?
I am having the same exact issue. Did you figure it out?
You said "Like portal" In the title and in portal the cube would actually be forward a few feet. Do you know how I can have it moved forward like in portal when I pick it up?
how do i initialize the holdArea variable? I keep getting compilers that that variable isnt initialized
i did the same thing but got this: Invalid worldAABB. Object is too large or too far away from the origin.
I can pick up and drop the object as intended, but I can't pick up any objects again after the first time , does anyone have any ideas as to why?
@SpeedTutor In the console it shows this ERROR "Argument 2 may not be passed with the "out" keyword" . Can anybody help me?
Amazing video! I have two questions, how could you stop the overshoot of the object that happens when it gets picked up, and how would you make a set distance of how far away the object is being held from you
To set the distance, just move the object we parented to our camera. To stop the overshoot you could try and adjust the settings on the rigidbody! :)
Is there a way you can show me like holding a key and placing it where the doorknob is? it could have something to do with set active true and false. Sorry, I'm just bad with coding. Great tutorial btw!
You could have a trigger or collider on the door area, when the key you have picked up enters that area. You could open the door, parent the key to the door or potentially make the key move to the doors position. Something like this! :)
@@SpeedTutor I see. I'll try that!
Edit: Wow! It works! :D. I actually doubted myself that I could pull that off. I have no experience in coding but pulling that off feels very satisfying. Thank you!
Hey, Im having issue with the code, whenever i go to pick up the object, the object im trying to pick up dissappears
Nvm i did = instead of - on line 43
Haha, good job on fixing it! :D
@@SpeedTutor thanks :)
Hey, I have question. After I've done the script, it shows " pickup force is assigned but its value is never used ", why is it so ?
i pickup the object once then drop it and then it doesnt want to pick it up again, everything was set back to normal and it has box collider and rigidbody
Happens with all objects?
Hey, the script works great but I'm wondering how did you do the little bounce when picking up the object?
Hey there, I'm not really sure about that. It wasn't intentional. See if you can see what my Rigidbody settings are, those might affect it, or maybe the distance my transition point is.
@@SpeedTutor Yeah It does seem to just happen but it does bug it out sometimes with really intense bouncing
is there a way to toss it like in portal?
ae you fling your camera very fast and let go of the block, the block goes far.
right now, the block just drops.
also the block clips through the ground and drops through the floor.
@WasNeverBrandon Did you ever fix this. I am having the same problem right now?
For some reason my raycast does not properly respond to objects in the game. At first I thought it was because most of the objects are empties with children being the models (since I'm designing the game to make it easy for swapping out models), but even when I tried to look at a standard cube I spawned in and gave a rigid body, the raycast still wouldnt detect it
Do you have colliders on everything? What about rigidbodies?
@@SpeedTutor I have them on the objects meant to be picked up, not the environment (like not on the floor but I assumed I shouldn’t)
It didnt work for some reason. Just doesent work. Can anyone please help? I checked every single letters of the code but i couldnt get it to work.
Any errors?
@@SpeedTutor Nope.
Is it a way to make it to where only I can pick it up and nobody else able to touch it even when I drop it
You could have different tags for different players? As in the other players can't interact with a particular tag?
@@SpeedTutor yea cause I made a pick up item and everyone can grab it but I wanna make it to where only I can touch it but idk what to do
If it’s okay can you please make a video about it I’m new to unity and don’t know much about the tags n stuff
I'd highly recommend you throw your question into ChatGPT and it will give you some structured advise on how to do it. Ask it some simple questions and it will really be the best bet! :)
@@SpeedTutor okay thanks
I need help, when I pick up an object the object freaks out on the y axis, when I walk it freaks out more
What about if you freeze that axis on the rigidbody?
This works great, however, with smaller objects and walls, if you go too fast, the force makes the object eventually clip through, this is more an issue on the engine in general than with the code but; how should I prevent that?
I though of detecting if the held item collides with something, reduce the heldforce to zero until it stops colliding, but no idea on how to to detect collisions on a referenced GameObj
You could increase detection for physics objects
@@SpeedTutor How do you do that? My object clips through and instantly gets launched away
I downloaded the project from the Patreon site, and it works great with FPSController. What changes would I have to make to this project to have a third person character pick up and drop the items?
What happens when you try a third person controller?
Thank you for this, I’ve been looking for away to pick up objects for the longest. 😁💪🏾 is there a way I could drop/let go of the obj to attach it to a post or wall?
I'm not sure on the most optimised way but you could create a trigger collider, when an object is inside it and you've let go of it. You could have it parent and/or transform to that object to place on a specific item. Something like that! :) Thanks for watching though!
@@SpeedTutor Hello again, the previous tip you gave me worked great thank you! is there a way to lock the Y position to the terrain? ive tried to RigidbodyConstraints.FreezePositionY but it still leaves the ground. its a machine and i just want it to roll on the floor.
Nice tutorial, but i'm having an issue, since i followed the tutorial, it works great, but my camera movements aren't smooth, they are jerky, an idea ?
Is this when you're picking something up?
This was amazing but could i please have the wole code because i got an error and i cant fix it for some reson
I have the code on my Patreon :)
@@SpeedTutor is it free?
how do you make object drop from hand on collision? like if I had a sword but once I touched the wall with the sword it would fall from my hand? im having trouble find a solution
You could do that if the sword collider intersects with another? You need one to have a rigidbody though. You could use collision enter. :)
@@SpeedTutor thanks for the speedy reply! but I can’t get it to override the grip of the controller? Should I momentarily shut off it’s rigidbody or something? Or a way to make the controller cancel its grip command? Ive glanced through the XR interactable script for the OPENXR stuffs but as you can imagine its YUGE! so Im having trouble zeroing in on the method.
help my object when i pick up is not in the right position and it's jittering like alot HALP
Is your empty gameobject point in the correct place? Increase some of the rigid body properties.
It doesn't seem to be working for me?
What happens? :O
Nvm I fixed it
im not sure what im doing wrong here but when i grab the object its scale changes
That's really strange, you don't affect the transform values - Do you?
@@SpeedTutor nope and I found a work around but now the work around has caused it to slightly change the scale when being grabbed but it will then revert back to it's original scale when being dropped
Should also mention since i left it out of my previous comment that the object was changing its scale when being dropped not grabbed
@@Jack-kv9qd Hi, I have this exact same problem... How did you fix this ?
@@Jack-kv9qd is your main camera size 1,1,1 ? if not, it might mess this up
Great tutorial, I just have a question:
the system works, but there is a rigidbody item that I don't want the player to be able to pick up. How do I make it so they can't?
You could make sure you can only pickup objects with tags, make sure to check for the tag before picking them up! :)
Ok thanks. Still very new to unity and C# as a whole so I'll see what I can do. I appreciate the reply!
Ugh, it goes trough the floor when I move mouse too fast
also walls and other items
Let's say you have a tree that falls on its side when you pick it up it's still on its side. What script would allow me to pick up an object and have it stand straight back up when its picked up?
You could use the same code but then rotate the transform of the object or something?
@@SpeedTutor I don't know what code that would be. The code in the video works but I'd need a code for a set rotation of object. Coding is such a drag.
Google, how to change the rotate of an object in Unity. You want to use Transform.Rotate
Doesn't work, maybe I'm to tired, maybe it's different version
Maybe you just need to give it a go. I made this really recently, It definitely works! :)
why is the code for holding an object so big and long
You can do very much with a couple of lines of code :)
Amazing tutorial but when I hold the object and look down it goes through the floor
Does it go through anything else?
Yes walls and cubes.
@@SpeedTutor Yo, it goes through walls, please give a fix
@@aeyempire Add a collider to the box
@@nemuruvia I already have a collider, just like the original comment my problem is that the collider doesn't work when I look down and it goes through the floor.
I'm getting an error: NullReferenceException: Object reference not set to an instance of an object. It's the first line of the DropObject function that it seems to have a problem with.
What's the line?
@@SpeedTutor heldObjRB.useGravity = true;
Is heldobjRB added in the inspector or is it found using GetComponent? I don't recall how I wrote it :)
@@SpeedTutor It’s not in the inspector no. In the previous function PickupObject() it’s found using GetComponent but in DropObject() there’s no GetComponent line
Assets\PickupController.cs(53,46): error CS0246: The type or namespace name 'RigidBody' could not be found ( are you missing a using directive or an assembly reference?) please help
You've spelt Rigidbody wrong, I think :)
@@SpeedTutor oh okay it is big B thanks
@@SpeedTutor sorry for asking again but i have also this error Assets\PickupController.cs(51,12): error CS0119: 'PickupController.PickupObject(GameObject)' is a method, which is not valid in the given context
Im having an issue at the Transform.Direction bit for the mouse button down part. It is saying that it doesn't exist in the current context, so what should I do?
Did you spell it correctly? :S
@@SpeedTutor Yeah but I figured out a solution, thanks anyway!
How did you fix it?
@@SpeedTutor I had to go back to an older version of unity
Little problem... everything works fine but i can pickup myself like my character and can fly all around the map and i want this work only on boxes
That's an amazing little bug! You could add "Ignore Raycast" to your character, that might help :) Also, you could add tags that the raycast will find before actually interacting with anything.
@@SpeedTutor i added tag to my box object and then used .compareTag and it worked
Amazing, you didn't even need my help! :P
What would I do if I want to only be able to pick up certain rigidbodies instead of all of them? I'm following your hinge door tutorial and when I press E I can pick up the door. Keep in mind I'm very new to Unity and coding.
You could detect a tag that your object has, rather than any rigidbody. Just make sure to check for the tag first! :)
@@SpeedTutor Okay I'll give that a try and update you when I try it
@@SpeedTutor Alright I tried it and it works. Thanks :)
@@dunderguy Hello, how are you ? That's crazy, I have the same problem, working on a gamejam project right now. How did you do it ? Thanks !
@@audiofrank6747 I made it to where if the object I want to pick up has a certain layer on it, (in my case the pickup layer) it picks it up.
Do I put "private void Update()" or "void Update()"?
do you need my code that I put? I got 9 other errors too.
private void Update is the same as void Update :)
It gave me an error
Can this work with the new input system?
Of course it can! :) It only has one single input so you can just change it for that. :)
@@SpeedTutor thanks! Would you help a newbie out? Did you have a tutorial that outlines how to go from the old input system to the new? I am familiar with setting up the bindings, but when it comes to code, yikes!
If you're not confident I would recommend to stick with the legacy input and then check out some tutorials on the new system because it is far more in-depth than just a single line of code! Sorry I can't be of more help but it's almost impossible to mention in on comment! Haha.
hi its me again, my code is not working, here is my code: using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickUpControler2 : MonoBehaviour
{
[Header("Pickup Settings")]
[SerializedFeild] Transform HoldArea;
private GameObject heldOBJ;
private RigidBody heldOBJRB;
[Header("Pickup Parameters")]
[SerializedFeild] private float pickupRange = 5.0f;
[SerializedFeild] private float pickupForce = 150.0f;
private void Update()
{
if(Input.GetMouseBottonDown(0))
{
if(heldOBJ == null)
{
RaycastHit hit;
if(Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, pickupRange))
{
PickupObject(hit.transform.gameObject);
}
}
else
{
DropObject();
}
}
if(heldOBJ != null)
{
MoveObject();
}
}
void MoveObject()
{
if(Vector3.Distance(heldOBJ.transform.position, holdArea.position) >0.1f)
} {
Vector3 moveDirection = (holdArea.position - heldOBJ.transform.position);
heldOBJ.AddForce(moveDirection * pickupForce);
}
void PickupObject(GameObject pickOBJ)
{
if(pickOBJ.GetComponent())
} {
heldOBJRB = pickOBJ.GetComponent();
heldOBJRB.useGravity = false;
heldOBJRB.drag = 10;
heldOBJRB.constraints = RigidBodyConstraits.FreezeRotation;
heldOBJRB.transform.parent = holdArea;
heldOBJ = pickOBJ;
}
void DropObject()
{
heldOBJRB.useGravity = true;
heldOBJRB.drag = 1;
heldOBJRB.constraints = RigidBodyConstraits.None;
heldOBJ.transform.parent = null;
heldOBJ = null;
}
}
what is wrong?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickUpController2 : MonoBehaviour
{
[Header("Pickup Settings")]
[SerializeField] Transform HoldArea;
private GameObject heldOBJ;
private Rigidbody heldOBJRB;
[Header("Pickup Parameters")]
[SerializeField] private float pickupRange = 5.0f;
[SerializeField] private float pickupForce = 150.0f;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
if (heldOBJ == null)
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, pickupRange))
{
PickupObject(hit.transform.gameObject);
}
}
else
{
DropObject();
}
}
if (heldOBJ != null)
{
MoveObject();
}
}
void MoveObject()
{
if (Vector3.Distance(heldOBJ.transform.position, HoldArea.position) > 0.1f)
{
Vector3 moveDirection = (HoldArea.position - heldOBJ.transform.position);
heldOBJRB.AddForce(moveDirection * pickupForce);
}
}
void PickupObject(GameObject pickOBJ)
{
Rigidbody pickOBJRB = pickOBJ.GetComponent();
if (pickOBJRB != null)
{
heldOBJRB = pickOBJRB;
heldOBJRB.useGravity = false;
heldOBJRB.drag = 10;
heldOBJRB.constraints = RigidbodyConstraints.FreezeRotation;
heldOBJRB.transform.parent = HoldArea;
heldOBJ = pickOBJ;
}
}
void DropObject()
{
heldOBJRB.useGravity = true;
heldOBJRB.drag = 1;
heldOBJRB.constraints = RigidbodyConstraints.None;
heldOBJ.transform.parent = null;
heldOBJ = null;
}
}
@@captaincyanide8432 i think hold area is broken
6:13
Is this so you can remember where you were? Haha.
@@SpeedTutor it works so
NullReferenceException: Object reference not set to an instance of an object
pickUpObject.PickupObject (UnityEngine.GameObject pickObj) (at Assets/Scripts/pickUpObject.cs:60)
pickUpObject.Update () (at Assets/Scripts/pickUpObject.cs:26)
I created an empty on my player and positioned it right in front of my player and attached it to the script. but i get this error when i click.
nevermind. intellisense kept changing my shit
Hhaa, good work on fixing it! :)
@@SpeedTutor thanks
Thanks for this tutorial too. Only issue i have now is sometimes when I pick up the object, it goes to the holdarea like it should but sometimes it gets right in the players face.
I'm getting an error when I try to pick up an object, code looks identical as far as I can tell and visualstudio doesn't see any issues, but I get
NullReferenceException: Object reference not set to an instance of an object
PickUpController.PickUpObject (UnityEngine.GameObject pickObj) (at Assets/Scripts/PickUpController.cs:56)
PickUpController.Update () (at Assets/Scripts/PickUpController.cs:25)
What's on line 56?
@@SpeedTutor Honestly I deleted it and started over, got it working now. I think the issue was with gameObject at line 25 in PickupObject(hit.transform.gameObject); it wasn't getting a reference for gameObject? I'm new so no idea honestly, but it's working now.
Great work on fixing it! :)