Use the upper, lower, left and right keys to control the ball direction, using the Enter_frame event to control the movement of the ball.
W = XX._WIDTH/2;
h = XX._HEIGHT/2;
Onenterframe = function () {
if (Key.isdown (37)) {
xx._x = Xx._x-speed;
else if (Key.isdown (39)) {
xx._x = Xx._x+speed;
else if (Key.isdown (38)) {
xx._y = Xx._y-speed;
else if (Key.isdown (40)) {
xx._y = Xx._y+speed;
}
Xmax = xx._x+w;
Ymax = xx._y+h;
Xmin = xx._x-w;
Ymin = xx._y-h;
if (Bg.hittest (xx._x, ymin, True)) {
Xx._y + = speed;
}
if (Bg.hittest (xx._x, Ymax, True)) {
Xx._y-= speed;
}
if (Bg.hittest (xmin, xx._y, True)) {
Xx._x + = speed;
}
if (Bg.hittest (Xmax, xx._y, True)) {
xx._x-= speed;
}
};
Speed = 2;
But this code increases the value of speed is problematic because of-= speed and + = speed.
So the right approach should be
Private Function Kdown (evt) {
if (evt.keycode==37) {
Key[0]=-speed;
else if (evt.keycode==38) {
Key[1]=-speed;
else if (evt.keycode==39) {
Key[2]=speed;
else if (evt.keycode==40) {
Key[3]=speed;
}
}
Use array key to record key state, and then use Enterframe to control movement.
Private Function Enterframe (evt) {
if (ship.x<0) {
key[0]=0;
else if (ship.x>550) {
key[2]=0;
else if (ship.y<0) {
key[1]=0;
else if (ship.y>400) {
key[3]=0;
}
ship.x+= (key[0]+key[2]);
ship.y+= (Key[1]+key[3]);
}
This is also the standard practice of AS3, above I am the detection of the film stage, can be replaced by detection collision.