使用processing.js在javascript中使用速度来移动矩形
Using velocity to move rectangle in javascript using processing.js
我正在使用javascript和processing.js制作一个简单的pong克隆。我已经为桨制作了类,然后将其扩展为由玩家控制的类。目前,我正试图实现播放器控制类内的键盘输入处理。我的意图是,当w
或s
被按下时,我通过玩家类中的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
相关文章:
- Canvas Html5绘图应用程序,移动画布会导致重大问题
- 正在SharePoint 2013母版页中添加JQuery移动文件
- 如何在android中使用phonegap将文件从一个文件夹移动/复制到另一个文件夹
- 使用PhoneGap计算移动人员的速度
- CSS使用鼠标使许多背景以不同的速度移动
- 玩家移动速度更快,增量时间更长
- 通过删除元素来提高谷歌地图API V3在移动设备上的速度
- 在jQuery或Javascript中是否有办法确定触摸移动事件的速度
- jQuery Animate - 以固定速度将 DIV 移动到 X、Y 位置
- Javascript以可变的角度和速度为元素移动制作动画
- 如何在移动设备上更改HTML5视频的播放速度
- 鼠标移动速度比工具提示快
- 移动速度JS在一个页面上
- HTML画布以恒定的速度在一个方向上移动一个对象
- 获得移动摄像机的速度
- 使用processing.js在javascript中使用速度来移动矩形
- 如何使svg对象以恒定速度在圆形轨迹中移动,D3.js
- 为光标提供移动速度
- 移动速度像按键事件
- 如何减缓移动引导旋转木马滑动滚动的滚动速度