Thursday, April 24, 2014


Move the ball with a specified angle


Move Ball With Specified Angle

//Script following below
<style>
#mainContainer{
margin:0px auto;
border:#F00 1px solid;
width:500px;
height:400px;
}
</style>
</head>

<body onload="init()">
<div id="mainContainer">
     <canvas height="400" id="gameCanvas" width="500">
<!-- Your browser not supported -->
</canvas>
    </div>
<script type="text/javascript">
var ang = 45;
var speed = 10;
var rad = ang*Math.PI/180;
var xInc = Math.cos(rad);
var yInc = Math.sin(rad);
var ctx;
var currentPosX = 50;
var currentPosY = 50;
function init(){
var c=document.getElementById("gameCanvas");
ctx = c.getContext("2d");
setInterval(startAnim,50);
}
function startAnim(){
currentPosX += xInc*speed;
currentPosY += yInc*speed;
if(currentPosX>480||currentPosX<20){
xInc *=-1;
}
if(currentPosY>380||currentPosY<20){
yInc *=-1;
}
ctx.clearRect(0,0,500,400);
ctx.beginPath();
ctx.arc(currentPosX, currentPosY, 20, 0, 2 * Math.PI, false);
ctx.fillStyle = 'green';
ctx.fill();
}
</script>
</body>

No comments:

Post a Comment