Make Things Move -- Javascript html5版(三)三角函数形式的动画

  角度制和弧度制浏览器

  生活中一般是用角度度来理解的,代码里都是用弧度制来计算。函数

  角度转弧度:DEG_TO_RAD = Math.PI / 180this

  弧度装角度:RAD_TO_DEG = 180 / Math.PIspa

  

 

  正弦:Math.sincode

  波形:blog

 

  y轴的值会在-1和1的区间波动,只要咱们指定一个范围值,好比50,乘于这个范围值就能获得一个在50~-50间的波形。应用于代码中,实现一个小球按正弦波运动的例子,设定相应的变量:seo

    angle: 角度(即x轴的值)it

    range: 范围(半径)io

    speed: 角速度 (x变化的速度)function

var SinWaveMove = __class__(Ball, {

    __init__: function () {
        Ball.call(this)
        this.init()
    },

    init: function () {
        // 设置球在浏览器的左中位置
        this.y = stage.height / 2

        this.angle = 0
        this.speed = 0.01
        this.range = 500
    },

    onenter: function () {
        this.x = Math.sin(this.angle) * this.range
    }

})

 

  余弦:Math.cos

  余弦的波形效果其实也差很少,能够本身实验一下,把上面的Math.sin替换成Math.cos便可.

 

 

  圆周运动

  其实就是正统函数和余弦函数配合使用,x轴的值用Math.sin算y轴的值用Math.cos算,共同的半径,同一个角度值来算。小球作圆周运动的例子:

var CircularWave = __class__(Ball, {

    __init__: function () {
        Ball.call(this)
        this.init()
    },

    init: function () {
        // 设置球在浏览器的中心位置
        this.x = this.cx = stage.width / 2
        this.y = this.cy = stage.height / 2

        this.angle = 0
        this.speed = 0.01
        this.radius = 500
    },

    onenter: function () {
        this.x = Math.sin(this.angle) * this.radius + this.cx
        this.y = Math.cos(this.angle) * this.radius + this.cy
    }

})

 

  椭圆运动

  实际上是圆周运动同样,只是把x轴和y轴的半径设置成不一样大小的值就OK了,能够本身试试。

 

  反正切:Math.atan2

  由于这个比较有用,用于计算出两点间的偏移角度:angle = Math.atan2(y2 - y1, x2 - x1)  // 这个获得的结果是弧度制的。

  一个箭头指向鼠标的demo:

var Arrow = __class__(Sprite, {

    __init__: function (attr) {
        Sprite.call(this, attr)
    },

    init: function () {
        this.x = stage.width / 2
        this.y = stage.height / 2
    },

    draw: function (ctx) {
// 画出一个红色的箭头 ctx.fillStyle
= 'red' ctx.beginPath() ctx.moveTo(-50, -50) ctx.lineTo(0, -50) ctx.lineTo(0, -100) ctx.lineTo(50, 0) ctx.lineTo(0, 100) ctx.lineTo(0, 50) ctx.lineTo(-50, 50) ctx.lineTo(-50, -50) ctx.fill() } }) var arrow = new Arrow() stage.add(arrow) var RAD_TO_DEG = 180 / Math.PI document.body.onmouseover = function (e) { var rotate = Math.atan2(e.y - arrow.y, e.x - arrow.x) arrow.rotation = rotate * RAD_TO_DEG }
相关文章
相关标签/搜索