角度制和弧度制
生活中通常是用角度度来理解的,代码里都是用弧度制来计算。
角度转弧度:DEG_TO_RAD = Math.PI / 180
弧度装角度:RAD_TO_DEG = 180 / Math.PI
正弦:Math.sin
波形:
y轴的值会在-1和1的区间波动,只要我们指定一个范围值,比如50,乘于这个范围值就能得到一个在50~-50间的波形。应用于代码中,实现一个小球按正弦波运动的例子,设定相应的变量:
angle: 角度(即x轴的值)
range: 范围(半径)
speed: 角速度 (x变化的速度)
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
}