GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Friday, April 1, 2011

JS - Simulation Of Gerak Peluru

<h1>Gerak Parabola</h1>
<p id="info" style="font: 12px sans-serif;">x: <span id="x"></span> | y: <span id="y"></span> | v: <span id="v"></span></p>
<canvas id="canvas" style="border: 1px solid blue;">Not Supported</canvas>
<div id="right" style="float: right; ">
 <table>
  <tr><td>Degree</td><td>:</td><td><input type="text" id="degree"/></td></tr>
  <tr><td>Initial Velocity</td><td>:</td><td><input type="text" id="velocity"/></td></tr>
  <tr><td>&nbsp;</td><td>&nbsp;</td><td><input type="button" value="Run" onclick="run()"/></td></tr>
 </table>
</div>
<script>
var Lucia = Lucia || {};
Lucia.GerakParabola = function(){

// screen dimension
this.screenWidth = 500;
this.screenHeight = 200;

// getting the elements
this.canvas = document.getElementById('canvas');
this.xInfo = document.getElementById('x');
this.yInfo = document.getElementById('y');
this.vInfo = document.getElementById('v');

// setting the initial condition
this.ctx = canvas.getContext('2d');
this.canvas.height = this.screenHeight;
this.canvas.width = this.screenWidth;
this.ctx.fillStyle = '#88f';

// box properties
this.width = 10;
this.height = 10;

this.vBefore = 60;
this.vHozAfter = 0;
this.vVerAfter = 0;
this.degree = 60;
this.g = 10;
this.xBefore = 0;
this.xAfter = 0;
this.yBefore = 0;
this.yAfter = 0;
this.dt = 0.1;
 }
Lucia.GerakParabola.prototype.move = function(){

// getting the velocity component
this.vHozAfter = this.vBefore*Math.cos(this.toRadian(this.degree));
this.vVerAfter = this.vBefore*Math.sin(this.toRadian(this.degree)) - this.g*this.dt;

// getting the position of horizontal and vertical
this.xAfter = this.vBefore*this.dt*Math.cos(this.toRadian(this.degree));
this.yAfter = this.vBefore*this.dt*Math.sin(this.toRadian(this.degree)) - 0.5*this.g*this.dt*this.dt;

// summing the time
this.dt = this.dt+1;

// update the box;
this.ctx.clearRect(0, 0, 500, 200)
this.ctx.fillRect(this.xAfter, this.screenHeight - this.yAfter - this.height, this.width, this.height);

// display info
this.xInfo.innerHTML = Math.round(this.xAfter);
this.yInfo.innerHTML = Math.round(this.yAfter);
this.vInfo.innerHTML = Math.round(this.vHozAfter);
 
// setting the timer
var lol = this;
setTimeout(function(){lol.move();},1000);         
}

// convert degree to radian
Lucia.GerakParabola.prototype.toRadian = function(degree){
 return (degree/57);
}
Lucia.GerakParabola.prototype.setDegree = function(d){
 this.degree = this.toRadian(d);
}
Lucia.GerakParabola.prototype.setInitVelocity = function(v){
 this.vBefore = v;
}

function run(){
 var degree = document.getElementById('degree');
 var velocity = document.getElementById('velocity');
 var gp = new Lucia.GerakParabola();
// gp.setDegree(eval(degree.value));
// gp.setInitVelocity(eval(velocity.value));
 gp.move();
}
</script>

Share/Bookmark

No comments:

Post a Comment