Unity 101: 5 ways to move Unity3D Objects
Vložit
- čas přidán 8. 09. 2024
- Check out the Course: bit.ly/2S5vG8u
-------
Discover 5 different ways to move your Unity3D gameobjects, see some of the differences between them, and learn which one I usually use.
More Info: unity3d.college
00:50 Transform SetPosition
01:21 Transform Translate
02:10 Rigidbody AddForce
03:46 Rigidbody MovePosition
04:43 Rigidbody SetVelocity
thank you.
thank you
thank you
As old as it is I think that this is one of the best tutorials that I have seen about this ever, great job.
so, use transform position if you don't use rigidbody, use rigidbody velocity if you use rigidbody, and use addforce if you want realistic push on an object. moveposition is rarely used, and transform translate works the same as transform position, but you can set the direction relatives.
I know this is a 4 year old comment, but I would disagree. You can have a rigidbody and still want to use transform position change in many cases, like a character mover. I would say ONLY use rigidbody velocity or addforce if you want realistic physics movement for things like bullets
I am new to Unity and I was wondering the differences between these methods myself. Thanks so much! I love the content you are putting out!
Now you can teach us
You should have a fixed update if you are handling rigidbodies
does fixed update make it so that you dont have to use time.deltaTime? or do you still?
When moving objects you should always use time.deltatime. It makes the movement more reliable because fixedupdate will fire more times per second on a faster computer compared to a slower one (as far as i understand). time.deltatime simply keeps track of the time between frames so you can rectify this difference.
Any physics movement should be done inside of fixed update.
Unity's internal physics system runs on the fixed update loop, so if you call changes to it inside of update it will get out of sync and eventually your collides wont be interacting correctly. Take a look at the provided image for a more detailed understanding of how this works
docs.unity3d.com/uploads/Main/monobehaviour_flowchart.svg
This should be one of the first things people learn when working with a new engine..
So, with fixed update does it prevent the values from getting jacked up and causing my object to move more than it was programmed to? To be more specific, when I start my game and, say, jump for example, my object will sky rocket into the air much higher than it normally does when jumping normally. Right now i'm using add force for my jump commands and while this issue could probably be rectified by giving the system time to load, I don't want it to do this ever if I decide to make it available to the public.
As an update to this I can indeed confirm that having fixed update fixed the issue.
This helped me out on a project I'm working on. Add Force with a rigidbody allows me to adjust the mass of a door so it looks realistic when it open and closes. Thanks for the video!
I love rick and morty man! great work! I had no idea you also did unity tutorials, also great.
Hey, I just wanted to provide a small correction since I and other comments seem to be confused about it:
At 3:05 you were right not to have time.deltaTime. AddForce specifically requires a parameter in Newton (in default mode ForceMode.Force). The physic system handles the timestep component.
To prove it you can just spawn a cube in a new scene with a rigidBody on it and default parameters (gravity on).
Then add a script to it with AddForce(mass * acceleration) in FixedUpdate(), where mass is the mass of the rigidBody and acceleration is the gravity but upward (9.81f * Vector3.up by default).
The result in playmode is that the cube doesn't move.
Since gravity is applied every physic cycle it means AddForce is compensating for it every cycle too behind the scene else the cube would move.
note that you can't do that in Update() even if you were trying to "hack" it by multiplying by Time.deltaTime/Time.fixedDeltaTime because the cube would have moved before having its momentum being canceled by the next FixedUpdate.
Im almos sure that you cant
Multiply by deltatime anywhere wich includes accerlation some way, because it just doesbt give right answers, thats not only physics based problem, its also if you try make something on your own.
There is formulas for accerlation calculating using deltatime, but it isnt as simble as multiplying by delta time. If movement is not accerlating then you can multiply by delta time, if its accerlating you cant. You need to use special formula to that
Fixed update on other hand works perfectly
BTW, I know this video is older than a lot of tutorials out there, but just wanted to know I really appreciate it and have turned to it many times.
Thank you so much, you have no idea how much I've been looking for something like this, since I can't find it in Unity's manuals,
this is such a huge help!
I forgot to add, my problem with my current script, is it rotates along the world's axis, so if my player turns around, the controls are inverted.
RigidBody.MovePosition works well with a RigidBody (doesn't have to be kinematic) in case you want to set a new position. The reason is that is uses the physics and actually does the same as setting the velocity with just the right amount to end up on the desired positon. So the physics can be properly resolved in case of collision, which is not the case with setting the transform position directly. This is the reason why in the example you can see the balls with Transform.SetPosition and Transform.Translate (which both set a new position ignoring the physics), both shake when they hit the wall: they are essentially teleporting to a new position and the physics cannot handle it (although the physics can still push the object outside of the wall if it doesn't overlap too much). The other methods (including RigidBody.MovePosition) use the physics and handle the collisions properly.
Thanks man. rb.Velocity saved my day today.
Yo, I've been looking for a video like this for a week. Thank you!!
you saved my sanity, thank you so much
The velocity/force should not depend on Time.deltaTime. Physics manipulation should be done in FixedUpdate. But besides that. Interesting video!
why that? i heard this a lot, but the only argument i've heard was that at high speed you can pass trough wall in update method, but i test it and if my normal speed is 6, i had to set it to 8 000 to pass trough a wall, i use CharacterController.Move, maybe that's related?
Dude! Dude! Thank you! Thank you for this informative, comprehensive & extremely beneficial tutorial. Where I have you been!
Thank you so much for this video , it has really helped me in my project
great visual presentation
Thank you so much for making this I was so confused 😅
Excellent work here! Thanx for taking the time to put this together and sharing it!
If you have a lot of colliders under a rigid body, then using rigidbody.MovePosition will save a lot of performance than changing position through transform.
Thanks Jason Thanks a lot Buddy. Love from India.
This is exactly what this newbie was looking for.
Very clean tutorial, thank you !
You're welcome, glad it was helpful :)
The reason the Transform is wiggling is because on every frame it pushes it self inside the collider, and every Fixed Update the Rigidbody pushes the object out.
Jason should really test Character Controllers here. Rigidbodies update on a fixed timer and if you want high frame rates are not a good option.
Awesomeness :) Learnt so much in this short crash course video :) Thanks Jason for sharing this info :)
Thanks man! I finally understand the velocity one
Great tutorial you are a really good teacher 👍
The most interesting question is how you move a object with "static collider" in 3D environment (which use the Physic engine). Exist two popular variants - make this object w/o Rigidbody and use Transform or attach to object the Kinematic RB and use the Rigidbody.MovePosition?
thanks no other tutorial showed set velocity so thanks.
thank you for being there for us 👍👌✌️
Great video, thank you, Jason!
on my top down shooter I used transform SetPosition but the movement looked laggy, then I switched to AddForce which made my movement much smoother and when I go from moving north to west it doesn't just snap move but makes a smooth transition
awesome video
I was gonna make the same scene to test them but u saved me some time THANKS
Great tutorial!
thanks for clearing this up!
Thanks, great info
Useful, thank you!
I'm sorry I'm sorry I'm soooo sorry but... has anyone ever told you that you look like Dan Harmon in your videos? Dude you get me every time....
transform.Translate worked for me! Thanks a bunch!!
Awesome differetiated!!
Did anyone notice why in the last simulation, the one with gravity, the third ball remains coming and going? I think the physics behind that is beautiful.
Oh man TNX big time for this tutorial!
hi, great stuff but you forgot to mention Vector3.MoveTowards?
that would be the same as transform.position as you would use vector3.MoveTowards as an input to that function. Hope that helps
Thank You! This is so helpful
Thank you so much! I was searching since a while to find the rigid body move script! You did an error in your script but it's simple to correct. Thank you
This is really useful!
guys why is there a error saying transform does not contain definition for foward
What method is giving you that error? It's difficult to debug code that you cannot see.
Didn't know Dan Harmon started doing Unity Tutorials
very helpful
Time.deltaTime on the SetVelocity is wrong, you have to feed it the desired velocity in m/s, using Time.deltaTime*50 makes it so that you have 1m/s only when having an fps of 50, making it framerate dependent, the very thing you are trying to avoid. (having lower framerate would actually make it faster since deltatime would be bigger)
thanks! Helpful video
Thank u Jason.
So you personally rarely use Rigidbody move position and here I am wondering why. It seems like the best option when using physics.
One of the most confusing things when I started learning Unity was whether or not to use a rigidbody to control my character. Most tutorials used transform.Translate but then you would see others saying "if something moves, unless it's a ghost or something, it is affected by physics and should have a rigidbody. If it doesn't have a rigidbody it shouldn't move!" So many people said to never directly manipulate an objects transform. But you say it's how you primarily do it? Or am I super confised about something. That's possible. That is so possible.
Depends a lot on if the object is being used by physics. Lots of things are just background items moving around ir things that aren't interacting with rogidbodies or colliders.
I made a new movement video btw showing a good free unity character controller for movement
@@Unity3dCollege thanks! I'll have a look.
Not sure in the previous version did not have this but I use Unity 2018.3.13 version and I can move a Kinematic type with velocity too.
I did do it on a 2D object, so maybe 3D Kinematic objects can't be moved via velocity.
So if I wanted boxes to randomly generate from the bottom of the screen to the top of the screen like bubbles. which one would I use? They would not interact with other objects generated.
Thanks so much, hope someone can help me.
Thanks a bunch
do you have a similar video about rotations? there are so many different functions for them and they confuse me a lot.
Why use deltaTime with AddForce? Aldo the rigidbody operations should be in the FixedUpdate not in the Update method
Great stuff
awesome, thx
Sir, is there anyway I can make a Transform translate motion smoother or
Make another rigidbody that can move forward toward any direction.
Please help me sir
how do you know which way is forward? I made a spaceship in unity and i want it to move sideways but it moves upward
Thanks a lot sir
thanks for the tutorial. one question, that code replacer where you renamed several things at once at around 4:30. how do i activate this?
I didn't know Dan Harmon does unity tutorials!
best tutorial on youtube.
Thanks Brother
Excellent UP UP
You should explain more since moving by Transform is dangerous in the way that you either send objects through objects or get that stupid bounce effect nobody wants. That's what makes Rigidbody movement preferred.
Would you please make a video about frames and how can we do animation within those frame like many VR drawing tools.
Cool video! I have one question tho: How can you use Transform SetPosition and don't get this "bouncing off" effect when hitting a collider?
Simply using rigid bodies (rigidbody.velocity)
Have you found aa solution? I´m asking myself the same Question now.
CZcams's automatic translation does not work
I have checked many videos, some of them are active and most of them are disabled and only show the English language and the rest of the languages do not show anything even though they are selected, your videos are also disabled.
hey, is it necessary to to the * Time.deltaTime for the rb.velocity method? If I don't do it, and just set a lower speed value, wouldn't I get the same result? I don't see how framerate would mess it up in this case...
Can Anyone tell me how to make it so like if I shoot the player moves in the opposite direction
Please tell me what is the best way (for good performance on mobile) when move non kinematic objects with rigidbody?
how do i make it to where an object moves one direction then goes back using addforce?
Not really relavent to the video, but to answer your question you would just want to inverse the force when it you want it to move back. You would addforce every update by some variable (i.e forceAmount), then for example after it colliders with something you could set the velocity to 0 and inverse the forceAmount variable so that it would move backwards.
or add the force on a single frame that is enough to bounce it off what you want to bounce off of, and add a bouncy physics material to your rigidbody
thank you both for your input. I will try both to see which would make the best results
I am making a carrom game. I want to hit the striker on pieces through keys? What code should I follow to hit
this helped me so much thank you (+1 Sub😁)
how do i set the velocity afterwards?(the ForceMult thingy)
Is there any way to remove the collision problem which occurs while using transform.position. I want to stick with transform.position ? I dont want to use rigidbody.addforce(). Please Check the move function in the script.
Hi Jason always watch but never post, having real but probably simple to yourself here goes: I have a UI Icon wind arrow that points in the direction of the wind which I set manually to say the x or -x direction and that force acts on the player and it pushes to that direction, great! BUT the UI Icon, when I try to move forward in the Z direction I can get UI Icon to move right facing the x direction I need or -x whatever, but when moving back the way in the -z direction the UI Icon stays the same direction always pointing the same way in x not going 180 flip; Ive tried if(player.transform.rotation.y == 180) or >0 etc etc and also if(player.transform.forward ) ==1) and ==-1 for what I thought was -z, but no tried many if statements many ways to get the icons to move in the desired direction when Im going in the z and -z direction but does not work, the closest I have is this:
if (Mathf.Abs(Vector3.Dot(Player.transform.forward, Vector3.forward)) == 1) { WindArrow.transform.Rotate(Vector3.forward, 180); }
and yey it works...or so I thought as the UI arrow rotates 180 every time I enter the OnTriggerEnter area is which activates the if code and being wrong again as it just keeps on flipping each enter no matter whcih way I face twice in thre z foe example grrr, then I tried this:
if(Mathf.Abs(Vector3.Dot(Player.transform.forward, Vector3.forward)) ==1 { aligned = true; ; }
{
if(aligned) { WindArrowL.SetActive(false); WindArrowR.SetActive(true); }else { WindArrowL.SetActive(true); WindArrowR.SetActive(false);
}
but the UI only shows up the else condition on both ways walking? I must be misunderstanding the if(Mathf.Abs(Vector3) code or something else, hopefully you can help I know you are busy or a fellow super geek can help moi lol Thanks guys 3 weeks of struggle a new record yey...or nae lol :D
how did do u stop the spheres when they hit the wall?
Thank's bro i like it
How did u create the texts in the ground?
help addforce wont work at all
Hey guys. Could someone help me? Whats the best way to move something like an elevator? I tried many ways but when my Character controller is standing on a rising platform he starts to shake (i'm guessing the elevator collider hits characters collider like in the video). Some say to parent the player from the elevetor onTriggerEnter but in my case it does nothing. I use standard Character controller for the player with applying vertical velocity for gravity in .Move() method I also use a SpereCast for ground checking, the elevator model only has a generated collider the one you get when importing an fbx model and right now I use Vector3.MoveTowards to move it up and down. Any help would be great thanks in advance.
Edit: after some experimentation I found that if my vertical velocity (gravity) is equal to 0 when I'm grounded, character just falls through the elevator, but if Y velocity isn't 0 (I have it at 6f) he doesn't fall but the stuttering occurs...
Is this secretly Dan Harmon
Anyone know how to move locally with velocity ?
EPIC
I have a strange issue right now. I use the set position on a transform like mentioned in the video.
It's called from another class every second. It should move by one per step. But what happens is that it doubles the old value every time and ads 1 on top.
So it moves from 1 to 3,7,15,31 and so on. Any idea why that happens? I bet I did some silly mistake but I have no idea what it.
send code
@@bigboobmasterbaiter69 I fixed it!. I called that function in another class with a coroutine.
And I called another function that triggered the coroutine again by accident.
That's why it always doubled up. For every start of the coroutine, it triggered one more time.
can someone tell me some uses for this i initially thought it can be used to move ai on set path during a cut scene but what are some other uses?
moving players, npcs, anything else that needs to move around during the game :)
Hi, how do you that shortcut to make new variable on 4:20?
Crtl-. (period) is what I use to create new variables. F2 is what i see at 4:20 though (rename)
How would I move them back and forth?
this is how
if (Input.GetKeyDown("w") && Input.GetKeyDown(KeyCode.LeftShift));
{
transform.position += transform.forward * Time.deltaTime * 2.5f;
}
if (Input.GetKeyDown("w"));
{
transform.position += transform.forward * Time.deltaTime;
}
if (Input.GetKeyDown("s") && Input.GetKeyDown(KeyCode.LeftShift));
{
transform.position -= transform.forward * Time.deltaTime;
}
how do you make it so it moves when u press a key like W
then replace the vector values with inputs.
hello sir, how i can transport only 50 pixels like chess moves t
Probably just using the Transform ways would work there. Sounds like you're not working with physics in that case?
I am trying to make a coin pusher game, but the coins just sit stationary on top of the moving shelf collider, and don't move with it. Then I tried using a script which adds a fixed joint on collision, but now the coins just freeze in place as soon as they touch the shelf. Can anybody help me?
try unity forums
@@BerrisGaming Already did, and already solved my problem. Feels good man. Now onto the next problem, lol
@@PatchCornAdams723 Yeah its problem after problem. If you run into something agian. Check gamedev.finiox.com for some tutorials.
@@BerrisGaming Lucky for me, I actually enjoy problem solving, and man this feels like a great way of learning. I can actually feel myself getting better at this with each problem. Thanks a lot btw, I will check out that forum immediately. Cheers!
It's amazing how much of a hard time I'm having with this in my 2D game. I'm trying to use a transform.position to a location of my mouse position that I'm grabbing via mousePosition = Input.mousePosition.
transform.position += (Vector3)direction * (defaultSpeed * Time.deltaTime);
This only works a few seconds, and then my character kinda sticks to one position and just speeds up and I can't have him walk another direction... Do I need to clear my mousePosition or something?
I've even tried it with Lerp such as...
transform.position = Vector2.Lerp(transform.position, direction, default_speed * Time.deltaTime);
...which honestly works the best except the further away I click from my sprite the faster he moves... At least he walks around in circles and where I want him to go..
Can anyone help me?
i'm not sure of how you set the whole function, but the way i would do it would be to set a Vector2 variable = (where the mouse click) and depending on how your code is organized you migth need to use LateUpdate function(will always be called after Update(or technicly before since it's a loop))
in 3D i use CharacterController.Move, i don't know if there's an equivalent in 2D, if not i would probably try with transform.translate which would probably look like this, sorry for the bad syntaxe:
public float = 6f;
Vector2 clickPosition = Vector2.zero;
Vector2 positionDifference = Vector2.zero;
Vector2 moveDirection = Vector2.zero
Update()
{
if(input.GetButtonDown("fire1"))
clickPosition = Input.mousePosition;
positionDifference = clickPosition - transform.position;
// i'm missing a part to normalize the value into moveDirection, i would have to test it out to be sure
transform.Translate(moveDirection * speed * Time.deltaTime);
}
don't take those line too seriously i'm just a begginer, but maybe it can give you some inspiration to solve your problem
Did he just create a presentation in unity???