Javascript 沿p5js中的圆弧移动
我在修复这部分代码时遇到了很多麻烦。我正在用P5js创建一个交互式图片。这幅画的一部分是太阳。我希望当鼠标在屏幕上来回移动时,太阳以弧形在屏幕上移动。像这样: 我的想法基本上是将鼠标映射到某个角度范围,然后使用该角度来计算太阳的位置,但我在绕圆周运动时遇到了很多麻烦 具体地说,我可以让一些东西循环移动,但我真的不知道如何改变这个圆的中心点。这是我的sun对象的代码,也是指向openprocessing上的草图的链接,您可以在这里看到它的实际操作并使用代码进行游戏:Javascript 沿p5js中的圆弧移动,javascript,graphics,geometry,processing,p5.js,Javascript,Graphics,Geometry,Processing,P5.js,我在修复这部分代码时遇到了很多麻烦。我正在用P5js创建一个交互式图片。这幅画的一部分是太阳。我希望当鼠标在屏幕上来回移动时,太阳以弧形在屏幕上移动。像这样: 我的想法基本上是将鼠标映射到某个角度范围,然后使用该角度来计算太阳的位置,但我在绕圆周运动时遇到了很多麻烦 具体地说,我可以让一些东西循环移动,但我真的不知道如何改变这个圆的中心点。这是我的sun对象的代码,也是指向openprocessing上的草图的链接,您可以在这里看到它的实际操作并使用代码进行游戏: function Sun(x
function Sun(x,y,w,h,c1,c2){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.c1 = c1;
this.c2 = c2;
this.center = createVector(width/2,height/2);
this.pos = createVector(this.x,this.y);
var dx = this.center.x - this.pos.x;
var dy = this.center.y - this.pos.y;
var initAngle = atan2(dx,dy);
this.angle = initAngle;
this.constant = height/2;
this.radius = dist(this.center.x,this.center.y,this.pos.x,this.pos.y);
this.display = function(){
noStroke();
fill(red(c1),green(c1),blue(c1));
//draw center point
ellipse(this.center.x,this.center.y,10,10);
var x = this.constant + sin(this.angle) * this.radius;
var y = this.constant + cos(this.angle) * this.radius;
ellipse(x,y,50,50);
this.angle = map(mouseX,0, width, initAngle, initAngle + PI);
}
}
提前感谢您的帮助,我只是有麻烦连接到我的旧高中几何代码 太阳中的第28行和第29行
var x = this.constant + sin(this.angle + HALF_PI) * this.radius;
var y = this.constant + cos(this.angle +HALF_PI) * this.radius;
把你的画改成这个
function draw() {
if(frameCount % 200 == 0) clouds.push(new Cloud());
sky.display();
sun.display(); // brought this line from bottom to behind mountains
mountain.display();
for(var i = 0; i < clouds.length; i++){
clouds[i].display();
if(!clouds[i].inBounds()){
clouds.splice(i,1);
}
}
}
函数绘图(){
如果(帧数%200==0)clouds.push(newcloud());
sky.display();
sun.display();//将这条线从底部带到山脉后面
mountain.display();
对于(var i=0;i
您可能需要查看
基本上,您有以下几点:
- 希望太阳围绕其旋转的中心点
- 您希望太阳旋转的角度
- 中心点与太阳之间的距离
cos()
和sin()
函数计算太阳的位置:
var sunX = centerX + cos(angle) * distance;
var sunY = centerY + sin(angle) * distance;
然后,唯一的问题是如何将mouseX
位置映射到角度。为此,可以使用map()
函数。map()
函数取两个值之间的角度(如mouseX
介于0
和width
之间),并将其映射到另一个范围(如角度的0
和2*PI
)。大概是这样的:
var angle = map(mouseX, 0, width, 0, 2*PI);
您可能会想玩一下这些值。使用0
和2*PI
将给您一个完整的循环。如果您只想要半个圆,您将需要使用类似于PI
和2*PI
的东西
更多信息请访问。ahhh,谢谢!我不明白我加在x和y上的常量值是中心点。这很有道理!非常感谢。