微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Processing / box2D中更改电动机的速度

如何解决在Processing / box2D中更改电动机的速度

我一直在使用“代码的本质”作为资源使用处理和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,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);
        stroke(0);
        ellipse(anchor.x,anchor.y,4,4);
    }
}

解决方法

速度变化应传达给关节。试试这个:

void SetMotorSpeed(float speed) {
     s.joint.setMotorSpeed(speed); // edited,processing/java uses camel-case
}

在命名变量时,您可能还需要多加注意。在您的原始帖子中,您对局部变量和成员变量使用了相同的名称,但这并没有想要的效果。大多数人对成员变量使用某种命名约定,以避免这种非常常见的错误。例如,所有成员变量都以“ _”开头

void SetMotorSpeed(float speed) {
    _speed = -speed; // speed is local!
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。