Moving an object along a straight line at a constant speed from point A to B

后端 未结 2 1046
清酒与你
清酒与你 2020-12-10 19:01

I know this has been asked a few times before, but there has been no answer that actually works that I can find. There is a similar one, but the speed varies dependi

2条回答
  •  悲哀的现实
    2020-12-10 19:44

    Live Demo

    Below are the basics required to get what you need working,

    var tx = targetX - x,
        ty = targetY - y,
        dist = Math.sqrt(tx*tx+ty*ty),
        rad = Math.atan2(ty,tx),
        angle = rad/Math.PI * 180;;
    
        velX = (tx/dist)*thrust;
        velY = (ty/dist)*thrust;
    
    player.x += velX
    player.y += velY
    

    This is a demo I did a while back which sounds like what you are looking for, I added the ability to click in order to change the target based off of your issue.

    window.addEventListener('mouseup', function(e) {
        targetX  = e.pageX;
        targetY = e.pageY;
    });
    
    var ctx = document.getElementById("canvas").getContext("2d"),
        x = 300,
        y = 0,
        targetX = Math.random()*300,
        targetY = Math.random()*300,
        velX = 0,
        velY = 0,
        thrust = 5;
    
    
    function draw(){   
        var tx = targetX - x,
            ty = targetY - y,
            dist = Math.sqrt(tx*tx+ty*ty),
            rad = Math.atan2(ty,tx),
            angle = rad/Math.PI * 180;;
    
        velX = (tx/dist)*thrust;
        velY = (ty/dist)*thrust;
    
        // stop the box if its too close so it doesn't just rotate and bounce
        if(dist > 1){
          x += velX;
          y += velY;
        }
    
        ctx.fillStyle = "#fff";
        ctx.clearRect(0,0,400,400);
        ctx.beginPath();
        ctx.rect(x, y, 10, 10);
        ctx.closePath();
        ctx.fill();
    
        ctx.fillStyle = "#ff0";
        ctx.beginPath();
        ctx.rect(targetX, targetY, 10, 10);
        ctx.closePath();
        ctx.fill();
    
        setTimeout(function(){draw()}, 30);   
    }
    
    draw();
    

提交回复
热议问题