如何在物体撞击的方向上移动物体(as3)?

时间:2016-04-24 11:32:09

标签: actionscript-3 flash

我有一个球和一个球员。我应该怎样做才能将球移向球员击球的方向?我尝试比较球员和球的x和y。但它没有用。

1 个答案:

答案 0 :(得分:0)

你应该发布一些代码到目前为止你尝试了什么...

我想如果有条件,你可以决定哪个应该是球的运动方向。我会给你一个提示:

if(player.hitTestObject(ball)) {
//if player hit the ball
//now you should see the possition of ball and of the player

//[we need some variables, you will see for what later on]
var x_direction, y_direction;

if(player.x < ball.x) { 
    //that means your ball is in the right , and player in the left 
    //and the ball should change position x with '+' sign --> (you will use this a bit latter when you will move the ball)
    //now we will use the x_direction variable to retain the direction in which the ball should move
    //because player is in the left (player.x < bal.x) that means the ball should move to right

    x_direction = 'right';
} 

else {
    //it's opposite ....
    //because player is in the right (player.x > bal.x) that means the ball should move to left

    x_direction = 'left';
}

//now we finished with x...we should check also the y axis

if(player.y < ball.y) { 
    //that means your ball is below the player 
    //player hit the ball from the top

    y_direction = 'down';
} 

else {
    //it's opposite ....
    //the ball should go up
    y_direction = 'up';
}


// now we have to move the ball
// we do this according to possition we checked before

if(x_direction == 'right') {
    //you should define your speed somewhere up like var speed = 10;

    ball.x = ball.x + speed; // remember the sign '+'?
    //or ball.x += speed;
} else {
    ball.x -= speed;
}

//and the same with y direction
if(y_direction == 'down') {
    //you should define your speed somewhere up like var speed = 10;

    ball.y += speed;
} else {
    ball.y -= speed;
}

// you can put this movement in an enterframe loop and make the movement....

}

希望这能帮助您实现目标......