Set DT (1/value)
<body> <head> <script type="text/javascript" src="guy.js"></script> <script type="text/javascript" src="lerp.js"></script> <script type="text/javascript" src="engine.js" defer></script> </head> <body> <h1>LERP Demo</h1> <canvas id="canvas" width="400" height="400" style="border:1px solid #000000;"></canvas> <p> Set DT (1/value) <input type="range" min="10", max="100" value="10" class="slider" id="delta" onchange="ChangeDT(this.value)" list="tickmarks"> <datalist id="tickmarks"> <option value = "10"></option> <option value = "50"></option> <option value = "100"></option> </datalist> </html> </body>
"use strict" let canvas = document.getElementById("canvas") canvas.tabIndex = 0 let guy = new Guy("canvas") guy.Radius = 10 guy.Pos = [10,10] guy.color="hsl(0,100%,50%)" let state = 0 let oldx = guy.xpos let oldy = guy.ypos let t = 0 let dt = 0.1 let targetx = 0 let targety = 0 ChangeDT(10) let handler canvas.addEventListener("click", MyHandler) guy.Draw()
"use strict" class Guy { constructor(canvasName, x=0, y=0, r = 20) { this.canvas = document.getElementById(canvasName) this.ctx = canvas.getContext('2d') this.xpos = x this.ypos = y this.radius = r this.color = "yellow" } get Color() { return this.color } set Color(c) { this.color = c } get Pos() { return [this.xpos,this.ypos] } get Radius() { return this.radius } set Pos(p){ this.xpos = p[0] this.ypos = p[1] } set Radius(r){ this.radius = r } Draw() { let cx, cy this.ctx.beginPath() this.ctx.fillStyle = this.color this.ctx.arc(this.xpos, this.ypos, this.radius, 0 , 2*Math.PI) this.ctx.fill() this.ctx.strokeStyle = "black" this.ctx.arc(this.xpos, this.ypos, this.radius, 0 , 2*Math.PI) this.ctx.stroke() } }
"use strict" function ChangeDT(amt) { dt = 1/amt } function LERP(a,b,t){ let rv = a*(1-t) + b*t return rv } function DoMove() { if (t < 1) { t += dt // clamp it between 0 and 1 t = Math.min(t,1) t = Math.max(0, t) let x = LERP(oldx, targetx, t) let y = LERP(oldy, targety, t) guy.Pos = [x,y] let angle = LERP(240,120, t) guy.Color = "hsl("+angle.toString() + ", 100%, 50%)" canvas.getContext('2d').clearRect(0,0,canvas.width, canvas.height) guy.Draw() } else { oldx = targetx oldy = targety window.clearInterval(handler) state = 0 } } function MyHandler(evnt) { if (state == 0) { targetx = evnt.offsetX targety = evnt.offsetY state = 1 t = 0 handler = window.setInterval(DoMove, 50) } }