- Home /
Implementing snake-like 2D controls and behavior
Hi, I'm totally new to Unity, and I'm trying to get the hang of it by creating a simple snake clone. So the controls I'm after are:
Each fixed time frame, snake advances a fixed distance in the direction it's currently looking,
left key changes the direction by -90 degrees around the z-axis,
right key changes it by +90 degrees.
I've got some code that sort of does that, but occasionally it makes 2 turns after a key is pressed instead of 1. Any ideas how I might fix this are much appreciated!
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
int ticks = 0;
int tickThreshold = 30;
float stepSize = 1.0f;
Vector3 nextDirectionChange = Vector3.zero;
void Start () {
transform.forward = Vector3.right;
}
void FixedUpdate () {
this.ticks++;
if (this.ticks > this.tickThreshold) {
transform.Rotate(this.nextDirectionChange);
transform.position += transform.forward * stepSize;
this.ticks = 0;
this.nextDirectionChange = Vector3.zero;
}
if (Input.GetKey(KeyCode.LeftArrow)) {
this.nextDirectionChange = Vector3.left * 90;
}
if (Input.GetKey(KeyCode.RightArrow)) {
this.nextDirectionChange = Vector3.right * 90;
}
}
}
As Getyour411 said, Get$$anonymous$$eyUp/Down will solve. But try not to do the input things in FixedUpdate(). They should run in Update().
Answer by getyour411 · Jan 26, 2015 at 05:07 AM
Use GetKeyUp/Down instead
Thanks, I'll try that! Could you explain why, or point me to some docs to help me understand? I get that Get$$anonymous$$ey fires all the time while the key is pressed and Get$$anonymous$$eyUp/Down only fires once per up/down action, but I was thinking that there wouldn't be a difference in behavior since I'm only using the input to set the nextDirectionChange
variable. As I see it, all that should happen is that nextDirectionChange
gets set multiple times -- the movement should only happen once every tickThreshold
ticks. What am I missing?