我目前正在开发基于svg画布的游戏,如图所示
现在我想做的是在比赛开始后允许球随机移动,但是我很难编码随机运动。
function createBall() {
const svg = document.getElementById("canvas")!,
ball = new Elem(svg, 'circle') #create the ball
.attr("cx",300).attr("cy",300)
.attr("r",8)
.attr('fill','grey');
Observable.interval(10).takeUntil(Observable.interval(4000)) #10 milliseconds until 4000 milliseconds
.subscribe( () => ball.attr("cx", 2 + Number(ball.attr("cx")))); #I'm having issue here when i subscribe as i can only allow the ball to move to the right at the moment, aside from being random
}
答案 0 :(得分:1)
我认为您需要在x和y坐标上朝某个方向恒定的速度。
我的建议是为x_velocity和y_velocity创建两个随机整数值。您可以尝试使用Math.random()和Math.floor():
function getRandomInt(min, max) {
return Math.floor((Math.random() + min) * Math.floor(max));
}
然后,如果方向为负(向左)或正(向右),则需要确定方向:
function getDirection() {
return this.getRandomInt(0, 2) === 0? -1 : 1;
}
使用这两个功能来设置x_velocity
和y_velocity
。现在,该球应该能够向左,向右,向上或向下移动了:
directionX = this.getDirection();
directionY = this.getDirection();
x_velocity = directionX * this.getRandomInt(1,8); // the number will be between -8 and 8 excluding 0
y_velocity = directionY * this.getRandomInt(1,8); // same here
Observable.interval(10).takeUntil(Observable.interval(4000))
.subscribe( () => {
ball.attr("cx", x_velocity + Number(ball.attr("cx"))); // the ball should go towards the left or the right
ball.attr("cy", y_velocity + Number(ball.attr("cy"))); // the ball should go up or down
);
快乐编码! :)