晴明的博客园 GitHub      CodePen      CodeWars     

[canvas] 边界与摩擦力

//返回一个介于min和max之间的随机数
Math.random() * (max - min) + min;

设置边界


var left = 0,
    top = 0,
    right = canvas.width,
    bottom = canvas.height;
	
if(ball.x > right){
    // do something
}else if(ball.x < left){
    //do something
}

if(ball.y > bottom){
    //do something
}else if(ball.y < top){
    //do something
}

边界环绕

当物体从一个边界消失,会从对立的边界出现。

边界反弹

var bounce = -1;
 if(ball.x + ball.radius > canvas.width){
        ball.x = canvas.width - ball.radius;
        vx *= bounce;
 }else if(ball.x - ball.radius < 0){
        ball.x = ball.radius;
        vx *= bounce;
 }
 if(ball.y + ball.radius > canvas.height){
       ball.y = canvas.height - ball.radius;
       vy *= bounce;
 }else if(ball.y - ball.radius < 0){
       ball.y = ball.radius;
       vy *= bounce;
 }

摩擦力

摩擦力的作用是减小物体的运动速度,
只需要定义一个变量f(代表摩擦力),
让速度在每一帧都减去它,直至为零

if(speed > f){
   speed -= f;
}else{
    speed = 0;
}
posted @ 2016-12-16 11:42  晴明桑  阅读(170)  评论(0编辑  收藏  举报