我一直在使用“代码的本质”作为资源使用处理和box2D制作一些简单的游戏。
我的问题是我到了一定程度,这些风车会根据电动机的速度顺时针/逆时针旋转(我正在使用PI/2
和-PI*2
)。我想要它,以便用户可以通过按键或鼠标按钮将此速度从正值更改为负值。环顾网上人们和box2D文档都说要使用功能void SetMotorSpeed(float speed);
,但是我没有运气确定如何实现此功能。我尝试了几种可以思考的方法,但是没有运气。
当前,我在主文件中有此文件(“ s”是风车实例的名称):
// Click the mouse to switch speed of motor
void mousePressed() {
s.SetMotorSpeed(s.speed);
}
我在风车文件中有这个:
//Set Motor Speed
void SetMotorSpeed(float speed){
speed = speed * -1;
}
但这不起作用。
我对编码还很陌生,这是我关于堆栈溢出的第一篇文章,因此如果我在询问或提出此问题方面做错了什么,我深表歉意。我乐于接受代码和礼节方面的建议!
这是整个风车的代码:
class Seesaw {
// object is two boxes and one joint
RevoluteJoint joint;
// float speed = PI*2;
Box box1;
Box box2;
float speed = PI*2;
Seesaw(float x, float y) {
// Initialize locations of two boxes
box1 = new Box(x, y-20, 120, 10, false);
box2 = new Box(x, y, 10, 40, true);
// Define joint as between two bodies
RevoluteJointDef rjd = new RevoluteJointDef();
Vec2 offset = box2d.vectorPixelsToWorld(new Vec2(0, 60));
rjd.initialize(box1.body, box2.body, box1.body.getWorldCenter());
// Turning on a motor (optional)
rjd.motorSpeed = PI*2; // how fast?
rjd.maxMotorTorque = 1000.0; // how powerful?
rjd.enableMotor = true; // is it on?
// Create joint
joint = (RevoluteJoint) box2d.world.createJoint(rjd);
}
// Turn the motor on or off
void toggleMotor() {
joint.enableMotor(!joint.isMotorEnabled());
}
boolean motorOn() {
return joint.isMotorEnabled();
}
void SetMotorSpeed(float speed){
speed = -speed;
}
void display() {
box2.display();
box1.display();
// Draw anchor just for debug
Vec2 anchor = box2d.coordWorldToPixels(box1.body.getWorldCenter());
fill(255, 0, 0);
stroke(0);
ellipse(anchor.x, anchor.y, 4, 4);
}
}
答案 0 :(得分:0)
速度变化应传达给关节。试试这个:
void SetMotorSpeed(float speed) {
s.joint.setMotorSpeed(speed); // edited, processing/java uses camel-case
}
在命名变量时,您可能还需要多加注意。在您的原始帖子中,您对局部变量和成员变量使用了相同的名称,但这并没有想要的效果。大多数人对成员变量使用某种命名约定,以避免这种非常常见的错误。例如,所有成员变量都以“ _”开头
void SetMotorSpeed(float speed) {
_speed = -speed; // speed is local!
}