使用velocity在javascript中使用processing.js移动矩形

时间:2013-03-14 15:48:52

标签: javascript html5 physics processing processing.js

我正在使用javascript和processing.js进行简单的pong克隆。我已经为拨片制作了课程,然后将其扩展为制作一个由演奏者控制的课程。目前,我正在尝试在播放器控制的类中实现键盘输入的处理。我的意图是当按下ws时,我通过玩家类中pVector变量表示的速度更新玩家桨的位置。

然而,当按下相应的键时,当前桨只会消失。

该脚本可以在jsfiddle here上看到,我的代码如下:

  // For reference
  // standard rectangle constructor is: rect(x, y, width, height);

    class Paddle
    {
        //width of paddle
        float pWidth;
        //height of paddle
        float pHeight;
        //initial paddle x coordinate
        float x;
        //initial paddle y coordinate
        float y;

        Paddle(float w, float h, float startX, float startY)
        {
            //set width
            paddleWidth = w;
            //set height
            paddleHeight = h;
            //set start x
            x = startX;
            //set start y
            y = startY;
        }

        void update()
        {
        }

        void draw()
        {
            //draw and fill rectangle with white
            fill(255)
            rect(x,y,paddleWidth,paddleHeight)
        }
    }

    class Player extends Paddle
    {
        Player(float w, float h, float startX, float startY)
        {
            super(w,h,startX,startY);
        }
    }

    class PlayerOne extends Paddle
    {
        pVector playerVelocity = (0,0);

        PlayerOne(float w, float h, float startX, float startY)
        {
            super(w,h,startX,startY);
        }

        void update()
        {
            debugger;

            if(keyPressed)
            {
                if(key == 'w')
                {
                    y -= playerVelocity.y;
                }
                else if(key == 's')
                {
                    y += playerVelocity.y;
                }
            }    
        }
    }


    //array list to hold the player paddles
    ArrayList<Paddle> paddles = new ArrayList<Paddle>();
    //middle x and middle y
    float mx, my, pw, ph;

    void setup()
    {
        mx = width/2;
        my = height/2;
        pw = 10;
        ph = 50;

        player1 = new PlayerOne(pw,ph,10,10);
        player2 = new Player(pw,ph,385,10);

        paddles.add(player1);
        paddles.add(player2);

        size(400,400);
    }

    void draw()
    {
        background(0);
        fill(100,100,0);

        // update each paddle added to array list
        for(Paddle p: paddles)
        {
            p.update();
            p.draw();
        }
    }

我做错了什么?

更新:

在按下按键的条件后,我在行debugger处加了一个断点:if(keyPressed)。似乎如果按下一次键,则由于某种原因在每次更新时反复检测。

1 个答案:

答案 0 :(得分:2)

在处理IDE中它甚至不会编译......它应该是PVector而不是pVector,但是在jsfiddle中它编译...还需要使用new和PVectors。因此,玩家速度未正确初始化并且在添加到位置时会发生变化......尝试:

PVector playerVelocity = new PVector(1,1);

请注意,如果velocity为0,则不会移动,所以我使用了1。 HTH