-1
我綁使球這是一個div
反彈向左一旦從右邊過來,但它仍然回到右邊,我知道有太多許多類似的問題誰給了這個解決方案,但他們都在實施canvas
這不是我的情況,我這樣做的方式似乎是對的,但就像你可以在現場演示中看到球仍然回到右邊,在這裏是代碼:
var speed = 15,
directionTop = 1,
directionLeft = 1;
setInterval(function(){
var ballElement = document.getElementsByClassName('ball')[0],
containerElement = document.getElementsByClassName('mainDiv')[0],
playersTestRebounce = document.getElementsByClassName('player')[0];
if (ballElement) {
var boxLeftPos = ballElement.offsetLeft,
boxRightPos = boxLeftPos + ballElement.offsetWidth,
offsetContainer = containerElement.offsetWidth + 40;
offsetContainerTop = containerElement.offsetTop;
if (boxRightPos > offsetContainer) {
directionTop = 1;
directionLeft = -1;
}
if (boxLeftPos < -40) {
directionTop = 1;
directionLeft = 1;
}
if (ballElement.offsetTop > playersTestRebounce.offsetTop && ballElement.offsetTop < (playersTestRebounce.offsetTop + 70) && ballElement.offsetLeft < (playersTestRebounce.offsetLeft + 12)) {
directionTop = 1;
directionLeft = 1;
}
if (ballElement.offsetTop > 390) {
directionTop = -1;
directionLeft = 1;
}
if (ballElement.offsetTop < 0) {
directionTop = 1;
directionLeft = 1;
}
ballElement.style.left = (boxLeftPos + speed * directionLeft) + 'px';
ballElement.style.top = (ballElement.offsetTop + speed * directionTop) + 'px';
/*cordinators = getPos(ballElement);
console.log("ball X : "+ cordinators.y + " ball Y :" +cordinators.x);*/
/*random = Math.floor((Math.random() * 376) + 6);
if (boxLeftPos < -40 || boxRightPos > offsetContainer) {
ballElement.style.top = random + 'px';
} */
}
}, 100);
你不應該更改左右/在頂部或底部牆壁上彈跳時的右側運動;在左右牆彈跳時也不應改變上/下運動。 – AakashM
但它似乎以這種方式工作時,球從左到右,而不是在另一個方向! –
它將適用於從左到右的第一次反彈,因爲您在彈跳底部時設置directionLeft = 1 – dwana