- Home /
4 Direction Ball Movement
Hi, I've been looking for some time now but I cant seem to figure out how to roll a ball in only 4 directions (Up,Down,Left,Right). Does anyone know or have a code on how I can achieve this. I want to lock all diagonal movement as close as I can. Maybe to stop all motion before I apply my next key stroke? Please help!
Thank you,
I still want to keep it in a rigidbody form because my game revolves around it.
Thanks,
Answer by Leuthil · Dec 23, 2015 at 03:09 PM
You should be able to achieve this effect by setting the rigidbody's velocity directly.
// Change xSpeed and ySpeed to be whatever you want on whichever axises your game uses
rigidbody.velocity = new Vector3(xSpeed, ySpeed, 0f);
You would just have to make sure that when you are setting your xSpeed and ySpeed based on the player's directional input that they cannot have a value for both xSpeed or ySpeed (in other words, at least one of them would have to be zero).
Wow, exactly what I was looking for. Surprised I couldn't find such a simple function. Thank you very much.
Just a quick question, Is it possible to make it so the velocity increases or does it have to be s$$anonymous$$dy?
Thanks,
You would have to do your own kind of acceleration solution so that the amount of velocity you are applying increases over time. Depending on how fine-tuned you want the movement to be changes how easy or difficult it would be to implement this.
One way is to have your xSpeed/ySpeed add to itself every frame the desired key is pressed. Then when the key is no longer pressed you can set it back to 0. If you are adding velocity each frame make sure you add velocity multiplied by Time.deltaTime so that way the velocity increase would be consistent across different systems running at different framerates.
Your answer
Follow this Question
Related Questions
How to prevent diagonal movement on 2d-rigidbody script? 2 Answers
Moving a rigidbody towards the mouse position 1 Answer
Moving rigidbodies at random 1 Answer
Implementing Counter-Movement 0 Answers
rigidbody friction problem....HELP!! 1 Answer