簡體   English   中英

達到一定值后如何反轉該正方形的方向?

[英]How can I reverse the direction of this square after it reaches a certain value?

我正在嘗試創建一個空閑動畫,其中紅色矩形在循環中稍微來回移動。 由於某種原因,一旦它達到指定的閾值而不是繼續向相反方向移動,它就會停止。

我做錯了什么?

<canvas id="myCanvas" width="1500" height="500" style="border:1px solid #c3c3c3;">
        Your browser does not support the canvas element.
    </canvas>

    <script>
        var canvas = document.getElementById("myCanvas");
        var ctx = canvas.getContext("2d");

        // Spaceship structure 
        var shipWidth = 250;
        var shipHeight = 100;

        // Canvas parameters
        var cWidth = canvas.width;
        var cHeight = canvas.height;

        // Positioning variables 
        var centerWidthPosition = (cWidth / 2) - (shipWidth / 2);
        var centerHeightPosition = (cHeight / 2) - (shipHeight / 2);

        var requestAnimationFrame = window.requestAnimationFrame || 
                                    window.mozRequestAnimationFrame || 
                                    window.webkitRequestAnimationFrame || 
                                    window.msRequestAnimationFrame;
        function drawShip(){
            ctx.clearRect(0, 0, cWidth, cHeight);
            ctx.fillStyle = "#FF0000";
            ctx.fillRect(centerWidthPosition,centerHeightPosition,shipWidth,shipHeight);

                centerWidthPosition--;
                if (centerWidthPosition < 400){
                    ++centerWidthPosition;
                }

            requestAnimationFrame(drawShip);
        }
        drawShip();

    </script>



@TheAmberlamps 解釋了為什么要這樣做。 在這里,我為您提供了一個解決方案,以實現我相信您正在嘗試做的事情。

使用改變幅度的速度變量。 X 位置始終隨速度值增加。 速度改變屏幕邊緣的方向。

// use a velocity variable
var xspeed = 1;

// always increase by velocity
centerWidthPosition += xspeed; 

// screen edges are 0 and 400 in this example
if (centerWidthPosition > 400 || centerWidthPosition < 0){ 
    xspeed *= -1; // change velocity direction
}

我在你的 if 中添加了另一個條件,這會導致對象來回反彈。 刪除 || 后的選擇如果你不想這樣做。

您的函數陷入循環; 一旦 centerWidthPosition 達到 399,您的條件會使其增加回 400,然后減少回 399。

這是另一個作為腦筋急轉彎的問題-通過使此動畫在循環中彈跳將如何進行-基本上將文本轉換為粒子,然后反轉回文本並反轉回粒子並返回文本等等,無限循環:

 var random = Math.random; window.onresize = function () { canvas.width = window.innerWidth; canvas.height = window.innerHeight; }; window.onresize(); var ctx = canvas.getContext('2d'); ctx.font = 'bold 50px "somefont"'; ctx.textBaseline = 'center'; ctx.fillStyle = 'rgba(255,255,255,1)'; var _particles = []; var particlesLength = 0; var currentText = "SOMETEXT"; var createParticle = function createParticle(x, y) {_particles.push(new Particle(x, y));}; var checkAlpha = function checkAlpha(pixels, i) {return pixels[i * 4 + 3] > 0;}; var createParticles = function createParticles() { var textSize = ctx.measureText(currentText); ctx.fillText(currentText,Math.round((canvas.width / 2) - (textSize.width / 2)),Math.round(canvas.height / 2)); var imageData = ctx.getImageData(1, 1, canvas.width, canvas.height); var pixels = imageData.data; var dataLength = imageData.width * imageData.height; for (var i = 0; i < dataLength; i++) { var currentRow = Math.floor(i / imageData.width); var currentColumn = i - Math.floor(i / imageData.height); if (currentRow % 2 || currentColumn % 2) continue; if (checkAlpha(pixels, i)) { var cy = ~~(i / imageData.width); var cx = ~~(i - (cy * imageData.width)); createParticle(cx, cy); }} particlesLength = _particles.length; }; var Point = function Point(x, y) { this.set(x, y); }; Point.prototype = { set: function (x, y) { x = x || 0; y = y || x || 0; this._sX = x; this._sY = y; this.reset(); }, add: function (point) { this.x += point.x; this.y += point.y; }, multiply: function (point) { this.x *= point.x; this.y *= point.y; }, reset: function () { this.x = this._sX; this.y = this._sY; return this; }, }; var FRICT = new Point(0.98);//set to 0 if no flying needed var Particle = function Particle(x, y) { this.startPos = new Point(x, y); this.v = new Point(); this.a = new Point(); this.reset(); }; Particle.prototype = { reset: function () { this.x = this.startPos.x; this.y = this.startPos.y; this.life = Math.round(random() * 300); this.isActive = true; this.v.reset(); this.a.reset(); }, tick: function () { if (!this.isActive) return; this.physics(); this.checkLife(); this.draw(); return this.isActive; }, checkLife: function () { this.life -= 1; this.isActive = !(this.life < 1); }, draw: function () { ctx.fillRect(this.x, this.y, 1, 1); }, physics: function () { if (performance.now()<nextTime) return; this.ax = (random() - 0.5) * 0.8; this.ay = (random() - 0.5) * 0.8; this.v.add(this.a); this.v.multiply(FRICT); this.x += this.vx; this.y += this.vy; this.x = Math.round(this.x * 10) / 10; this.y = Math.round(this.y * 10) / 10; } }; var nextTime = performance.now()+3000; createParticles(); function clearCanvas() { ctx.fillStyle = 'rgba(0,0,0,1)'; ctx.fillRect(0, 0, canvas.width, canvas.height); } (function clearLoop() { clearCanvas(); requestAnimationFrame(clearLoop); })(); (function animLoop(time) { ctx.fillStyle = 'rgba(255,255,255,1)'; var isAlive = true; for (var i = 0; i < particlesLength; i++) { if (_particles[i].tick()) isAlive = true; } requestAnimationFrame(animLoop); })(); function resetParticles() { for (var i = 0; i < particlesLength; i++) { _particles[i].reset(); }}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM