- Home /
Drag and jump mechanics?
I'm new to Unity and have been searching for a tutorial for a 2D game where one 1. drags (with mouse or finger) and 2. releases. On release the player jumps towards a certain point in a certain speed, depending on angle and reach of the drag. Hope this description makes sense. Thank you for reply! :)
Answer by RustyCrow · Aug 16, 2018 at 10:23 PM
unity 2d trajectory prediction <-- this is the keywords you need to goggle to get the knowledge needed. It is a complicated enough question to the point where getting code that exactly fits your criteria is going to be hard to find or atlaset understand for someone new(people getting paid to make this :P), or if you are very lucky maybe a kind soul can help you out with som free code.
I would say understand the math behind what you are asking is the Key to the problem, once you understand the Equation(formula ?) you find/plug the values(angle and force) you need from the mouse/finger.
i hope i dont come off as a a**hole i just dont think people gonna give you free code and if that was what you were expectation this place isnet going to be very helpful.
I hope this will help you get on the right track with your problem and pleas dont get scared of asking question, just keep in mind this is a place to solve problems together, not can someone make this game, mechanic or whatever for me. Its hard to ask/formulate a good question (i know to well :D)
No worry, thank you for reply! No, of course I understand and I wouldn't ask someone to work for free. I thought maybe there was a shortcut similar to beginners lessons of "2D Game $$anonymous$$it" that one could get into really easily. Thanks again :)
Answer by rainChu · Aug 16, 2018 at 11:11 PM
Drawing a dotted line predicting the player's jump trajectory is complicated, but actually getting those physics to work aren't that picky. When the user presses and holds, mark the x,y coordinates that the click started. Each frame, draw a straight line from there to the current cursor location. When the user lets go, you can apply an impulse using the physics engine based on the starting position and where the cursor currently is. Take a vector representing the distance the cursor is currently offset from the starting point. Its magnitude is the force the user wants to jump with. Multiply it by some constant factor to adjust the power of jumping in general. You can then pass this vector to the RigidBody or RigidBody2D using the AddForce method. Be sure to set the force type to Impulse, or it won't behave as expected.
For 3D physics systems: https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html
For 2D physics system: https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddForce.html