我正在为游戏学习html5。我需要随机移动一个球。现在,球从左移到右,并且玩家知道了球的位置。我需要球随机移动。
我附上了我正在使用的代码。关于随机速度和角度有些遗漏,我不怎么写。我正在使用simplegame.js
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src = "simpleGame_1_0.js"></script>
<script type="text/javascript">
var scene;
var sprite1;
function init(){
scene = new Scene();
sprite1 = new Sprite(scene, "brand1.png", 90, 90);
sprite1.setMoveAngle(45);
sprite1.setSpeed(10);
scene.start();
} // end init
function update(){
scene.clear();
//handle events here
//update all the sprites
sprite1.update();
}
</script>
</head>
<body onload = "init()">
</body>
</html
我没有看到simplegame.js
代码,但是如果在您提供的页面上定义了变量,则可以使用包含随机数的变量。
Math.random();
返回一个从0到不包括1的随机数。然后,您可以将该数字乘以最大值。
好像您首先在init()
方法中初始化代码(例如,设置比赛场地),然后可以使用update()
函数更新序列。
尝试这样的事情:
<script type="text/javascript">
var scene;
var sprite1;
function init(){
scene = new Scene();
sprite1 = new Sprite(scene, "brand1.png", 90, 90);
sprite1.setMoveAngle(45);
sprite1.setSpeed(10);
scene.start();
} // end init
function update(){
scene.clear();
//handle events here
//update all the sprites
// Here comes the extra code:
var randomAngle = parseInt(Math.random() * 90); // Random from 0 to 90 degrees
var randomSpeed = parseInt(Math.random() * 100); // random from 0 to 100 speed
// Not sure if needed but,
// the parseInt makes an integer
// (a value of 0,1,2,3,...n)
// Now pass the variables into the functions of the sprite (the functions are of
// the sprite object and will change its behaviour)
sprite1.setMoveAngle(randomAngle);
sprite1.setSpeed(randomSpeed);
// End of extra code
sprite1.update();
}
</script>
它行得通吗?
PS安装Firebug for FireFox可能非常有用,因此您可以看到一个显示错误消息的窗口。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句