利用Cocos Creator制作函数曲线—正弦函数
原理
代码
cc.Class({
extends: cc.Component,
properties: {
lineNode: cc.Node,
//振幅
amplitude: 1,
//周期
cycle: 1,
//波形与x轴位置关系或横向移动距离
offsetX: 0,
offsetY: 0,
},
// LIFE-CYCLE CALLBACKS:
onLoad () {
this.drawLine();
},
drawLine () {
let line = this.lineNode.getComponent(cc.Graphics);
//设置线条宽度
line.lineWidth = 1;
//设置线条颜色
line.strokeColor = cc.Color.GREEN;
for (let i = 0; i <= cc.winSize.width; i += 1) {
let posY = this.createPoint(i);
if (i === 0) {
//创建线条起始点
line.moveTo(0, posY);
}
else {
//与前一段线条相连
line.lineTo(i, posY);
}
}
line.stroke();
},
createPoint (x) {
//将x转换为弧度
let result = this.amplitude * Math.sin(this.cycle * x * Math.PI / 180 + this.offsetX) + this.offsetY;
return result;
},
start () {
},
// update (dt) {},
});
节点摆放及参数调整
效果
拓展
对代码稍加改造可以模拟心电图玩
cc.Class({
extends: cc.Component,
properties: {
//振幅
amplitude: 1,
//周期
cycle: 1,
//波形与x轴位置关系或横向移动距离
offsetX: 0,
offsetY: 0,
},
// LIFE-CYCLE CALLBACKS:
onLoad () {
this.drawLine();
},
drawLine () {
this.lineNode = new cc.Node();
this.lineNode.parent = this.node;
this.lineNode.position = cc.v2(-cc.winSize.width / 2, 0);
let line = this.lineNode.addComponent(cc.Graphics);
//设置线条宽度
line.lineWidth = 1;
//设置线条颜色
line.strokeColor = cc.Color.GREEN;
this.count = 0;
this.schedule(() => {
line.clear();
for (let i = 0; i <= cc.winSize.width; i += 1) {
let posY = this.createPoint(i + this.count);
if (i === 0) {
//创建线条起始点
line.moveTo(0, posY);
}
else {
//与前一段线条相连
line.lineTo(i, posY);
}
console.log(posY);
}
this.count-=20;
line.stroke();
}, 1);
},
createPoint (x) {
let result = this.amplitude * Math.sin(this.cycle * x * Math.PI / 180 + this.offsetX) + this.offsetY;
return result;
},
start () {
},
// update (dt) {},
});