使用processing.js在javascript中使用速度来移动矩形

Using velocity to move rectangle in javascript using processing.js

本文关键字:速度 移动 js processing javascript 使用      更新时间:2023-09-26

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

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

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

  // 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)。似乎如果按一次键,由于某种原因,在每次更新时都会重复检测到它。

在处理IDE中它甚至不会编译…它应该是PVector而不是PVector,但在jsfiddle中它编译…你还需要使用new与PVectors。所以playerVelocity没有正确初始化,当添加到position时就会发疯…试一试:

PVector playerVelocity = new PVector(1,1);

注意,如果速度为0,则不会移动,所以我使用1。hth