- Home /
Movement stops working randomly
Hi, I'm developing a maze game and currently I'm working on coding the player. So far i've created a simple maze in which the player moves around. I've taken a few snippets from here and there.
The player moves forward until it reaches a collider, when it stops. I've used AddForce since the camera moves and rotates with the player so the world axis won't help.
#pragma strict
var rotateCounter : KeyCode;
var rotateClock : KeyCode;
var forwardMove : KeyCode;
function Update () {
if (Input.GetKeyDown(forwardMove)){
rigidbody2D.AddForce(new Vector2(transform.up.x*700, transform.up.y*700));
}
if (Input.GetKeyDown(rotateCounter)) {
rotateLeft();
}
if (Input.GetKeyDown(rotateClock)) {
rotateRight();
}
}
function rotateLeft() {
for(var i = 0; i<90; i+=2) {
yield;
transform.Rotate(0,0,2);
}
}
function rotateRight() {
for(var i = 0; i>-90; i-=2) {
yield;
transform.Rotate(0, 0, -2);
}
}
In a separate file, i've added the collision controls
function Update () {
if ( rigidbody2D.velocity.magnitude > 1 ){
Debug.Log("Moving");
var MoveScript = GetComponent.<MovementScript>();
MoveScript.enabled = !MoveScript.enabled;
}
}
function OnTriggerEnter2D(other: Collider2D) {
Debug.Log("Collision");
//The commented solution works fine too to stop the player
//rigidbody2D.AddForce(new Vector2(transform.up.x*700*-1, transform.up.y*700*-1));
rigidbody2D.velocity = Vector3.zero;
}
The second file disables any input until the player reachs a wall in order to prevent rotations in the middle of a run and here comes my problem. I can wander arond a few times and then suddently stops working. My input doesn't come back so the game "freezes"
I don't want to add rigidbodys to the walls since the colliders are a few pixels separated from the "physical" walls.
What can make my code stop working? Thank you in advance for your help :)
Is the 'Debug.Log("Collision")' happening? if so, why not enable the script there:
rigidbody2D.velocity = Vector3.zero;
GetComponent($$anonymous$$ovementScript).enabled = true;
Answer by Aridez · Feb 20, 2014 at 03:55 PM
You could try using velocity instead of addforce:
if (Input.GetKeyDown(forwardMove)){
rigidbody2D.velocity = new vector2(5, 5); //5 is just an arbitrary value change it so it suits you
}
I would also move this code to fixedupdate() instead of update(): Look here And hope this helps!
Velocity doesn't works for me since I need a relative value of X and Y. The camera rotates with my character so the world's axis may differ from the player's axis.
Still, I changed from Update() to FixedUpdate(), thank you very much!