How to Do Grid Based Movement [Unity Tutorial]
#UnityTutorial #Unity3D #Comp3interactive #GameDev Everyone loves a good retro game, and a lot of those retro games used grid based movement for their players and enemies... In this video I'm going to show you exactly how to do it in your games!
Join me and learn your way through the Unity Game Engine, the C# language and the Visual Studio editor. Remember, if this video was useful then DROP A LIKE! 👍
SPONSORED LINKS:
www.gigatank3000.com
/ gigatank3000
💬 Join the Discord community here:
/ discord
📱 Find us on social media for more Tips and Tricks:
/ comp3interactive
/ comp3interactive
📱 Play our games for FREE here on Google Play:
bit.ly/2TisAQo
☕ Did I help you out? Feeling generous? Consider buying me a coffee/beer🍺😍: / comp3interactive
Пікірлер: 133
Love this video, each time I bring this topic people stare at me like I'm a weirdo xD I didn't saw many tutorials about it so really cool stuff, thank you!
This is exactly what I was looking for! Clearly explained and easy to follow. Thank you for sharing this information!
Thanks ! Best tutorial of grid movement, way simple to use and modify than any other.
Thanks man! knowing the solution now looks so easy, but I swear I tried in every way XD
Very helpful! Thanks so much!
omg bro, u dont know how much u helped me. thank u x1000.
Best video I have seen on grid movement! Thank you so much! So helpful
Thanks bro, you helped me a lot!
Awesome video! Thanks so much!!
Perfect! Thanks for this !
Making a mario party style board game, this has helped me a lot for a starting point, thank you!
Thank you for for the video, Mike, it was very informative and well done! I was trying to do something like this for a little prototype and I ended up finding DOTween on the asset storewhich is very simple to use and has a lot of capabilities of doing something like this also. Another tool for the old belt. Thank you!
WOW. Thanks a lot for this tutorial. ❤️❤️❤️ From India
lovely video mate
Hello there! Thank you so much for this great tutorial! It has been very helpful... +_+
Thanks so much for this tutorial
@comp3interactive
3 жыл бұрын
No worries man. Hope it helps
@Cyber-Gyn
Жыл бұрын
@@comp3interactive Could someone please post the code here, the codes
Thanks for the great and easy to follow tutorial!
Great job dude! hope you could do more about database and multi-player in Unity ❤🤘 Keep doing bro!
Great video
Thank you man so much!!!! This kind of movement was exactly what I was looking for, but question ... I'm a beginner and I yet have trouble understanding the code, but if I would want the player object to rotate exactly to 90 degree in the direction pressed and keep that rotation till the direction is changed ? Imagine like a mini tank xD. Once more thank you for this amazing tutorial!! cheers
great video :)
Hey I'm still kinda new to Unity, but why did you use a coroutine for the movement method instead of just a normal method?
Hello i would like to ask you know some good implementation of flood fill algorithm colouring texture in unity?Same way this does.
great tutorial, how do you change the distance of how far the character moves? when i move the character using your code, it moves and stops a lil too far past the tile
Hope you can share more about chating in game
Perfomance wise i think is better to put something like if(isMoving) return; instead of checking continuosly 4 if statement not a big performance save but a better practice overall or even if(!isMoving){ if(left) if(right) if(down) if(up) }
@comp3interactive
3 жыл бұрын
Good shout man, can't believe I didn't catch that 😂
@Milianati
3 жыл бұрын
Hi, thank you for taking time to correct this, I'd like to use your optimized version, but I gotta admit I'm confused, where am I supposed to write this ? About your first proposition "If(isMoving) return; ... I don't understand it, can you explain a bit more ? (I did understand your second proposition btw)
@FinnTG
3 жыл бұрын
@@Milianati Return simply stop method execution in that exact line of code no code below that return; will be executed if the "if" is true be carefull with the returns cause they could stop important code from being executed if you have more things that need to be checked the second one is safer to use
@Milianati
3 жыл бұрын
@@FinnTG Ooooh, alright, thank you ! I'll use it wisely !
@Cyber-Gyn
Жыл бұрын
@@comp3interactive Could someone please post the code here, the codes
Amazing! Thank you! How can I translate it to touch (for Android) instead of keyboard inputs?
How do u know what Vector3 the targetPos is?
so i don;t need create a grid I don;t nedd to know where is my current position I think you gave me a motivation to continue game dev and gave me a chance to play another week of Arma3 77 altis server )
Using Vector3.MoveTowards() is also another option for this type of movement.
how can I implement this for an ai, kinda new to unity and wanted to have a grid base movement for my enemies
thanks
Thank you for this tutorial, your implementation is great! I have added to your script to allow diagonal movement, animations, and adapted it to use the new input system and impassable tiles. Hope this helps someone: using System; using System.Collections; using UnityEngine; using UnityEngine.Tilemaps; public class PlayerController : MonoBehaviour { [SerializeField] private Tilemap baseTilemap; [SerializeField] private Tilemap impassable; [SerializeField] private Animator animator; private Vector3 direction; // Store direction Vector3 for passing to functions. private Vector3 targetPOS, originalPOS; private bool isMoving; private float timeToMove = 0.2f; //Required by Input System (This may vary depending on the name of your Action Input Control) //----------------------------------------------------- private PlayerInput playerInput; private void Awake() { playerInput = new PlayerInput(); } private void OnEnable() { playerInput.Enable(); } private void OnDisable() { playerInput.Disable(); } //------------------------------------------------------ // This check the grid position before the player moves to see if it is occupied by an impassable tile or if a tile exists in the desired location. // Requires UnityEngine.Tilemaps; //------------------------------------------------------------ private bool CanMove(Vector2 direction) { Vector3Int gridPosition = baseTilemap.WorldToCell(transform.position + (Vector3)direction); if (!baseTilemap.HasTile(gridPosition) || impassable.HasTile(gridPosition)) return false; else return true; } //------------------------------------------------------------ private IEnumerator MovePlayer(Vector3 direction) { isMoving = true; float elapsedTime = 0; originalPOS = transform.position; //Diagonal movement //When two input keys are pressed simultaneously for movement the input value is .71 or negative -.71 for two directional values. //this could move the player off of the grid. We check for this value and if it is true, set the values for the direction to 1 instead. //Also reduce the speed of the player when moving diagonally. //-------------------------------------------------------------- if (direction.x > 0 && direction.x direction.x = 1f; if (direction.x > -1 && direction.x direction.x = -1f; if (direction.y > 0 && direction.y direction.y = 1f; if (direction.y > -1 && direction.y direction.y = -1f; if (MathF.Abs(direction.x) > .1f && MathF.Abs(direction.y) > .1f) timeToMove = .3f; else timeToMove = .2f; //-------------------------------------------------------------- targetPOS = originalPOS + direction; while (elapsedTime { //Animate movement here. animator.SetFloat("Speed", 1f); animator.SetFloat("Horizontal", direction.x); animator.SetFloat("Vertical", direction.y); transform.position = Vector3.Lerp(originalPOS, targetPOS, (elapsedTime / timeToMove)); elapsedTime += Time.deltaTime; yield return null; } transform.position = targetPOS; isMoving = false; } private void Update() { //Check for input from the player each update. Vector2 input = playerInput.Player.Move.ReadValue(); if (playerInput.Player.Move.IsPressed() && !isMoving) { //Player is pressing move input, set the direction vector as a new Vector3. direction = new Vector3(input.x, input.y, 0); //Check to see if the player can move into the next transform position. Takes a Vector3 to validate movement against the tile map. if (CanMove(direction)) { StartCoroutine(MovePlayer(direction)); } } else if (!playerInput.Player.Move.IsPressed() && !isMoving) { //Player is not pressing input or moving, stop animations here. animator.SetFloat("Speed", 0f); } } }
@Cyber-Gyn
Жыл бұрын
Could someone please post the code here, the codes
great tutorial, the accent only makes it better
Thank you for this simple, but great, video. Exactly what i needed. Now i just have to figure out how to interact with the tilemap colliders 😅
Can I ask how can I limit player to walk on grid only since my player can move out from map
Great tutorial. Just starting with Unity myself so a newbie question but how would I implement diagonal movement here..?
@comp3interactive
3 жыл бұрын
Hi man. Sorry for the late reply, just catching up on some comments. I hope you don't need this help anymore and you've sorted it already but diagonal would need you to check for both KeyCode.W && KeyCode.D to move upper right diagonally for example. Just a few extra if statements for each of the 4 diagonal directions. Then lerp both the X and Y values by 1 instead of just one of the axis
Very helpful tutorial, tho how to make that grid tho? Or is it just a normal platform and not a grid?
This is really helpful and I tend to use it moving forward. Here is a question, when moving the character through holding down a button instead of tapping you can notice a jitterness of the player. I have a camera that follows the player and once removed that jitter goes away but I can test the camera and it is not the source of the problem or from what I can tell. It just does not seem to enjoy this movement. Is there something I can do to fix this issue?
@Mr.SilentOne
2 жыл бұрын
I believe the jitter the camera is picking up is the slight hesitation of the player before moving again. How do I fix that?
Confinement to a grid helps make tighter systems imo
How can i add some colliders?
is there anyway to do this using Applyforce instead?
Hi thanks for the tutorial. If we add more than one player, do you know how to move both simultaneously and don't collide each other?
How did you make the grid? Did you use a script?
My object when it moves it gets laggy with a follow camera does anyone know Why?
Hi, Thanks for the tutorial, Please help. I'm receiving three of these same errors on lines, 31, 36, & 41 Assets\Scripts\GridMovement.cs(41,19): error CS1061: 'Transform' does not contain a definition for 'postion' and no accessible extension method 'postion' accepting a first argument of type 'Transform' could be found (are you missing a using directive or an assembly reference?)
@comp3interactive
2 жыл бұрын
You spelled "position" wrong
@fishoscine1220
2 жыл бұрын
@@comp3interactive Derp, thank you so much. Noob here, it's working great now, except the scale of the movement relative to my asset (tile) seems off. Is there an easy way to make each movement 3.3 unity units? Thank you, again. Your new subscriber :)
@comp3interactive
2 жыл бұрын
Instead of multiplying your movement by 1 just multiply by 3.3f instead
I'm using this grid movement thing edited for something. You'll see the something at some point.
@comp3interactive
3 жыл бұрын
Got my eyes peeled my dude 👀
What if you want the target point to be on a smaller distance ? thx for your tutorial
@comp3interactive
3 жыл бұрын
Currently it's working on the basis of a 1x1 grid, but you can change the target areas to be anything you like really, so instead if using Vector2.one and adding that to the current position to get your target you can just add a custom Vector2(x, y) to your current position to move on a 2x2 grid or 0.5x0.5 grid for example
Awesome! Do you have a tutorial to use this with mouse movement?
@jestersgamestudio7517
2 жыл бұрын
create buttons that when clicked activate your movement coroutine
why we have to use coroutines?
Hi, I want to know how you initially line up the red square into a grid?
@comp3interactive
3 жыл бұрын
Each square is just 1x1 unit, the centre square is positioned at 0, 0, 0 and so is the red square
It kind of worked for me! And I really like the feel, because it feels more "systemized" than the freemoving movement we usually see! However, I feel like the player is "walking" on a far smaller grid than the one in my game! The size of my tilemap-grid thing is I think 2 or 3 units square? Rather than perhaps the 1 unit you usually use...May I ask for a way to edit the code to suit this need? Thank u!!
@comp3interactive
3 жыл бұрын
Hey man. Yeah that's easy enough to change, when you start the Movement coroutine, instead of passing in Vector3.left / Vector3.up etc, just pass in your own premade Vector3. Vector3.up is just a shorthand way for saying Vector3(0,1,0) so if you declare 4 Vector3 variables in your script with the grid sizes you need and use those instead. For example Vector3(0,2,0) passed in to Movement will move double the distance upwards
@carpiioo.806
3 жыл бұрын
@@comp3interactive ohh ok! That makes so much sense! thank you so much!! I'm new to Unity and C# coding in general, so in an attempt to make it double I did "Vector6" LOL!!! hahahahahah
@carpiioo.806
3 жыл бұрын
@@comp3interactive It works so well!!! Thank you so much!
@comp3interactive
3 жыл бұрын
😂 Yeah I remember thinking the same with the Vector thing when I started 😂. Glad it works man
and what about colliding with objects? Like in an RPG a rock / house / end-of-map wall ?
@comp3interactive
2 жыл бұрын
Raycast out from your player 1 unit in the direction you want to move, if your Ray hits something then don't run the movement code
Using a tilemap of 16x16 tiles how do I change this script so I don't fly through 4-5 tiles at once?
@mikkeljensen8824
2 жыл бұрын
not sure how I missed the similar question below and you have answered it "Hey man. Yeah that's easy enough to change, when you start the Movement coroutine, instead of passing in Vector3.left / Vector3.up etc, just pass in your own premade Vector3. Vector3.up is just a shorthand way for saying Vector3(0,1,0) so if you declare 4 Vector3 variables in your script with the grid sizes you need and use those instead. For example Vector3(0,2,0) passed in to Movement will move double the distance upwards"
Can I use Vector2 ?
would it be possible to apply it to an enemy that follows you? is that I have tried but without result.
@comp3interactive
3 жыл бұрын
Yeah it's possible, you can just pick a target position and move your enemy using A* pathfinding and limit each movement to the grid
Hello :) Do you know how to do this with mouse control ? :/
am trying to make something like this and I have 0 knowledge in programming, I tried to apply that in Bolt and failed miserably...
how to do this with grid size pixel specific
What would i change to increase the movement per keypress can someone help?
@Spider-
3 жыл бұрын
or can u link the image you used for the background
When I use the script I get an error saying: "Vector3 Does not contain a definition for 'lerp'". What should I do?
@comp3interactive
3 жыл бұрын
Use a capital L in Lerp
@Super_Claire
3 жыл бұрын
@@comp3interactive That fixed it! Thanks!
Thanks for this one, really helped. But one question. If I have multiple blocks to move. I end up with moving all of them at once. How can I solve this problem?
@comp3interactive
3 жыл бұрын
You mean you want to move all the cubes with a timing offset? If so you'd need a manager script that references all the blocks and run a coroutine which iterates over them all with a Wait For Seconds
@alexeyorekhov3982
3 жыл бұрын
@@comp3interactive no quite. I am saying I have multiple blocks. And I want to move only the one I have pressed on, so that other blocks will stay where they are. Right now they all move, my guess is because the same script is attached to each one of them
@comp3interactive
3 жыл бұрын
Yeah, okay, in that case you'll need to keep a reference of the block you want to move and pass it to a global coroutine and just move that one rather than running the move coroutine 9n everything
nice video, what keyboard do you have?
@comp3interactive
2 жыл бұрын
For this video I had a Razer Chroma but I've since changed to a Logitech Mx Keys for tutorials so you guys don't need to hear my clicky keys 😂
@leonstansfield
2 жыл бұрын
@@comp3interactive they sounded good aha
@comp3interactive
2 жыл бұрын
I think you're the only person to ever say that, most people in my discord said it was distracting so I swapped out
@leonstansfield
2 жыл бұрын
@@comp3interactive haha, I gotta appreciate a nice sounding keyboard!
Movement works great but I am having an issue when using this movement alongside 2D tilemap colliders. The player character is still able to clip through the colliders. Anybody else experience this and have any solutions. Much appreciated.
@samuelguedes6981
3 жыл бұрын
is because in this code he made there is no collision system, you will need to adapt
This is a great tutorial but i cant seem to get my character to stay in bounds of my map no matter what and he won’t collide with anything even when i use raycast2D :/
@letsplaynay9936
2 жыл бұрын
Use booleans for your transition point values
Hello, great video but one thing, the movement doesn't work well with colliders. I am able to walk through walls.
@comp3interactive
3 жыл бұрын
With this kind of movement I'd suggest using raycasting rather than relying on actual collider contact
I follow your tutorial but it didnt work on mine. It doesnt move anywhere :(
hey man this is exactly what I was looking for. do you know what should I add to make the character to move and slide through the tiles until it hits an obstacle?
@letsplaynay9936
2 жыл бұрын
Your best bet for obstacles would be ray casting. However , if you want to make wall boundaries, just make booleans for each direction (up, down, left , right) and trigger the boolean false when your player reaches a certain transition point depending on where you want the grid to end to prevent them from going passed the map and only allow the moveplayer coroutine to be ran if those specific booleans are set to true depending on the direction you are going. Thats what worked for me atleast
free movement is fine unless the levels are built in such a way that standing one pixel too far to the left or right stops you from going through a gap.
Didn't know that Jeremy Clarkson was doing Unity tutorials
@comp3interactive
3 жыл бұрын
They're some of the best tutorials... In the woooorld
hi was just wondering can you use this kind of movement with unity,s own Axis system e.g:vertical. your video was awesome btw. much appreciated
The movement works but there's no smooth walking animation. All I get is a delay before teleporting to the target position.
@Drivinefire
3 жыл бұрын
perhaps your movement is inside a FixedUpdate function? Fixed update can create delays like that when it comes to movement, make sure it is inside an Update function
@prokeikas7284
3 жыл бұрын
@@Drivinefire thanks, but it's not in fixedupdate.
@Drivinefire
3 жыл бұрын
@@prokeikas7284 Then idk man.. I'd have to take a look at the code. Try starting a project from scratch, I don't know why but that fixes half of the bugs I encounter
Does not work for me : Error CS ,0201, 0019
Any reason why my player isn’t moving with this code
@petipois28
Жыл бұрын
make sure you are pressing the WASD keys and not the arrow keys :D
Thanks for this! One question, how can we make the player collide with wall/edge?
@letsplaynay9936
2 жыл бұрын
You can either use raycasting or booleans for your transition point values. I suck at raycasting so what I did was make 4 canmove booleans for up, down, right, left and triggered them to false when my player's transition point hit a certain value and reached the end of the wall. I made it to the where the moveplayer coroutine can only be ran if canmove boolean is set to true depending on the direction they are moving
I would recommend using tweening library for this kind of movement. It becomes way easier and performant.
@comp3interactive
3 жыл бұрын
Most tweening libraries use this method, one one very similar, under the hood
Could someone please post the code here, the codes
but how do i make the grid?
@comp3interactive
3 жыл бұрын
That's just alternating coloured sprites
@Plutonium2000
3 жыл бұрын
@@comp3interactive thx
atleast provide source code
For optimizalisation i changed your 4 if statements into 4 smaller lines of code: private void Update() { CheckForMovement(KeyCode.W, Vector3.up); CheckForMovement(KeyCode.A, Vector3.left); CheckForMovement(KeyCode.S, Vector3.down); CheckForMovement(KeyCode.D, Vector3.right); } private void CheckForMovement(KeyCode pressedKey, Vector3 target) { if(Input.GetKey(pressedKey) && !isMoving) { StartCoroutine(MovePlayer(target)); } }
@comp3interactive
3 жыл бұрын
Nice work dude, I like that
@rickynijland3721
3 жыл бұрын
@@comp3interactive Well thanks for the tip! I could not find a nice system to make it feel responsive without it :D
9/11
where source code
Hey m8 could you upload the code so lazy kids like me can Ctrl + V