- Home /
method for grid movement
I'm currently working on a rouguelike, where I want movement similar to legend of grimrock, or the newer chocobo's dungeon game. I've tried using iTween, lerp, grid move, and moveTowards to move a test block in the dungeon, but i run into at least one of 4 problems.
the block teleports to the area, rather than moving smoothly.
the block doesn't move at all
the block move's smoothly, but when you take your finger off the key the block stops before centering on the next tile, or goes past it slightly.
the code doesn't properly check for collisions
I have some code I worked on recently, using moveTowards, and I get problem 3:
using UnityEngine; using System.Collections;
public class controllerscript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
bool moving= false;
Vector3 endposition= transform.position+ (Vector3.forward);
if(Input.GetKey(KeyCode.W) && moving==false){
moving=true;
transform.position=Vector3.MoveTowards(transform.position, endposition , Time.deltaTime);
moving=false;
}
}
}
I'd like the cube to snap to the tiles like with typical grid movement, but so far I haven't had any luck. Any ideas?
Thanks in advance!
Answer by robertbu · Nov 27, 2013 at 04:49 PM
Here is a rewrite of your code that solve most of your issues. Depending on your game, this may have issues with collisions. If so, look at Rigidbody.MovePosition() to solve the issue:
using UnityEngine;
using System.Collections;
public class ControllerScript : MonoBehaviour {
public float speed = 1.0f;
private Vector3 endpos;
private bool moving = false;
void Start () {
endpos = transform.position;
}
void Update () {
if (moving && (transform.position == endpos))
moving = false;
if(!moving && Input.GetKey(KeyCode.W)){
moving = true;
endpos = transform.position + Vector3.forward;
}
transform.position = Vector3.MoveTowards(transform.position, endpos, Time.deltaTime * speed);
}
}
The code works perfectly, even with collisions. Thanks so much :D
Hi .. I have an object that moves in the form of a grid, by touching it on the phone. How do I write code to move the unit left, right and forward?
Your answer
![](https://koobas.hobune.stream/wayback/20220613122926im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
A node in a childnode? 1 Answer
Crash on Microphone.Start() in AudioManager::getRecordPosition() 3 Answers
Parse Online Storage fails to communicate -1 Answers