AS2 acceleration please help

2 posts Page 1 of 1
Contributors
User avatar
backo
Just Registered
Just Registered
Posts: 6
Joined: Thu Dec 02, 2010 9:43 pm

AS2 acceleration please help
backo
i have a problem with my acceleration script in AS2

the script goes:
Code: Select all
onClipEvent(load){
	v1 = 1 //makes variable that = 1
}
onClipEvent(enterFrame){
	if(Key.isDown(Key.LEFT)){
		v1 +=2                     //increases variable
		this._x -= v1           //moves object using variable as speed
	} 
	if(Key.isDown(Key.RIGHT)){
		v1 += 2                   //increases variable
		this._x += v1          // moves object in the oposite way using the variable as speed
	}
	if(v1 > 10){
		v1 = 10                  // stops variable from increasing above 10
	}
}
but then it will acceletare up until 10 and if i let go of the button and press it again it will not accelerate up again, it will start at 10
ive tried to have a "else v1 = 1" behind both the if statemens, but then it will go slow as buck if i dont hold both buttons.

is there anything i can do for deceleration?

please help me, thanks.
Backo
User avatar
Twiffler
Member
Member
Posts: 46
Joined: Wed Sep 22, 2010 10:50 pm

Re: AS2 acceleration please help
Twiffler
Hi! I think I have a solution for you, just copy and paste this code into the movie clip your trying to move.
Code: Select all
onClipEvent (load) {
	// defining the variable is more efficient 
	var speed:Number = 2; // how fast it goes and speeds up
	var thisX:Number = 0; // were the movie clip is
	var friction:Number = 0.8; // optional deceleration for he movie clip
	var keydown:Boolean = false; // tells if the key is down for the max speed
}
onClipEvent (enterFrame) {
	this._x += thisX; 
	thisX *= friction; //slows down movie clip
	if (Key.isDown(Key.LEFT)) {
		thisX -= speed; // adds to movie clips _X
		keydown = true;
	} else {
		keydown = false;
	}
	if (Key.isDown(Key.RIGHT)) {
		thisX += speed;
		keydown = true;
	} else {
		keydown = false;
	}
	
	if (speedX>10 && keydown == true) { // if a key is down then it will check if its going to fast
		speed = 0; // it will stop adding to the movie clips location
	} else { // speed must be more than zero... so thats why there is the boolean keydown
		speed = 2; // resets the speed to original
	}
}
I tried to explain it some, you can change the variables around to get what you are looking for.
Lol i was thinking of cars while writing this, hoped this helped :D
2 posts Page 1 of 1
Return to “Tutorials”