草庐IT

javascript - 如何在 Canvas 中创建障碍

coder 2023-08-07 原文

我正在尝试制作一个像游戏这样的简单平台游戏。我使用的代码如下所示

window.onload = function(){
	var canvas = document.getElementById('game');
	var ctx = canvas.getContext("2d");

	var rightKeyPress = false;
	var leftKeyPress = false;
	var upKeyPress = false;
	var downKeyPress = false;
	var playerX = canvas.width / 2;
	var playerY = -50;
	var dx = 3;
	var dy = 3;
	var dxp = 3;
	var dyp = 3;
	var dxn = 3;
	var dyn = 3;
	var prevDxp = dxp;
	var prevDyp = dyp;
	var prevDxn = dxn;
	var prevDyn = dyn;
	var playerWidth = 50;
	var playerHeight = 50;
	var obstacleWidth = 150;
	var obstacleHeight = 50;
	var obstaclePadding = 10;
	var G = .98;
	var currentVelocity = 0;
	var obstacles = [];
	var imageLoaded = false;

	document.addEventListener("keyup",keyUp,false);
	document.addEventListener("keydown",keyDown,false);

	function keyDown(e){
		if(e.keyCode == 37){
			leftKeyPress = true;
			if(currentVelocity > 2){
				currentVelocity -= .1;
			}
		}
		if(e.keyCode == 38){
			upKeyPress = true;
		}
		if(e.keyCode == 39){
			rightKeyPress = true;
			if(currentVelocity < 2){
				currentVelocity += .1;
			}
		}
		if(e.keyCode == 40){
			downKeyPress = true;
		}
	}
	function keyUp(e){
		if(e.keyCode == 37){
			leftKeyPress = false;
		}
		if(e.keyCode == 38){
			upKeyPress = false;
		}
		if(e.keyCode == 39){
			rightKeyPress = false;
		}
		if(e.keyCode == 40){
			downKeyPress = false;
		}
	}
	function createObstacles(){
		for(x=0;x < 4;x++){
			var obX = (200 * x) + Math.round(Math.random() * 150);
			var obY = 50 + Math.round(Math.random() * 400);
			obstacles.push({"x":obX,"y":obY});
		}
	}
	createObstacles();
	function drawObstacles(){
		ctx.beginPath();
		for(x=0;x < 4;x++){
			var obX = obstacles[x].x;
			var obY = obstacles[x].y;
			ctx.rect(obX,obY,obstacleWidth,obstacleHeight)
		}	
		ctx.fillStyle = "grey";
		ctx.fill();
		ctx.closePath();
	}
	function initPlayer(){
		ctx.beginPath();
		ctx.rect(playerX,playerY,50,50);
		ctx.fillStyle="orange";
		ctx.fill();
		ctx.closePath();
	}
	function KeyPressAndGravity(){
		checkObstacleCollision();
		playerX += currentVelocity;
		if(rightKeyPress && playerX + 50 < canvas.width){
			playerX += dxp;
		}
		if(leftKeyPress && playerX > 0){
			playerX -= dxn;
		}
		if(upKeyPress && playerY > 0){
			playerY -= dyn;
		}
		if(downKeyPress && playerY + 50 < canvas.height){
			playerY += dyp;
		}
		if(playerY+50 < canvas.height){
			playerY += G;
		}
		if(playerX <= 0){
			currentVelocity = 0;
		}else if(playerX + 50 >= canvas.width){
			currentVelocity = 0;
		}
		dxp = prevDxp;
		dyp = prevDyp;
		dxn = prevDxn;
		dyn = prevDyn;
		G = .98;
		if(currentVelocity != 0){
			if(currentVelocity > 0){
				currentVelocity -= .01;
			}else{
				currentVelocity += .01;
			}
		}
	}
  /*-----------------------------------------------------------
  -------------------------------------------------------------
  -------------------------------------------------------------
  ---------------------------Check this part-------------------
  -------------------------------------------------------------
  -------------------------------------------------------------
  -------------------------------------------------------------
  ------------------------------------------------------------*/
	function checkObstacleCollision(){
		var obLen = obstacles.length;
		for(var x=0;x<obLen;x++){
			var obX = obstacles[x].x;
			var obY = obstacles[x].y;
			if((playerX + playerWidth > obX && playerX + playerWidth < obX + obstacleWidth || playerX > obX && playerX < obX + obstacleWidth) && playerY + playerHeight > obY - obstaclePadding && playerY + playerHeight < obY){
				dyp = 0;
				G = 0;
			}else if((playerX + playerWidth > obX && playerX + playerWidth < obX + obstacleWidth || playerX > obX && playerX < obX + obstacleWidth) && playerY > obY + obstacleHeight && playerY < obY + obstacleHeight + obstaclePadding){
				dyn = 0;
			}else if(playerX + playerWidth > obX - obstaclePadding && playerX + playerWidth < obX && ((playerY + playerHeight > obY && playerY + playerHeight < obY + obstacleHeight) || (playerY > obY && playerY < obY + obstacleHeight))){
				dxp = 0;
			}else if(playerX  > obX + obstacleWidth && playerX < obX + obstacleWidth + obstaclePadding && ((playerY + playerHeight > obY && playerY + playerHeight < obY + obstacleHeight) || (playerY > obY && playerY < obY +  obstacleHeight))){
				dxn = 0;
			}

		}
	}
	function draw(){
		ctx.clearRect(0,0,canvas.width,canvas.height);
		initPlayer();
		KeyPressAndGravity();
		drawObstacles();
	}

	setInterval(draw,15);
}
<canvas id="game" width="1000" height="600" style="border:1px solid #000;"></canvas>

问题是有时当“玩家”的速度很高时,它可以像下图那样穿过障碍物。我怎样才能阻止这种情况发生?

所以我想要的是玩家应该在到达障碍物时立即停下来,而不是穿过障碍物

最佳答案

对快速移动的物体进行碰撞测试会很复杂

您必须确定您的玩家和障碍物是否在移动过程中任何时候相交——即使玩家在移动结束时已经越过障碍物。因此,您必须考虑玩家从移动开始到移动结束的完整路径。

...

然后您可以通过检查玩家的轨迹是否与障碍物相交来检查玩家在移动过程中是否与障碍物相交。

一种相对有效的快速移动物体碰撞测试方法

  1. 定义连接玩家起始矩形的 3 个顶点的 3 条线段,这些顶点最接近玩家的结束矩形。

  1. 对于与障碍物相交的 3 条线中的任何一条,计算线段到障碍物的距离。选择起始顶点和障碍物之间距离最短的直线。

  1. 计算所选线段的“x”和“y”距离。

    var dx = obstacleIntersection.x - start.x;
    var dy = obstacleIntersection.y - start.y;
    
  2. 将玩家从其起始位置移动#3 中计算的距离。这导致玩家移动到它第一次与障碍物碰撞的地方。

    player.x += dx;
    player.y += dy;
    

代码和演示:

代码中有用的函数:

  • setPlayerVertices 确定连接玩家起始矩形的 3 个顶点的 3 条线段,这些顶点最接近玩家的结束矩形。

  • hasCollided 找到连接玩家起始位置顶点与障碍物碰撞点的最短线段。

  • line2lineIntersection 找到 2 条线之间的交点(如果有的话)。这用于测试开始到结束线段(从#1 开始)与构成障碍物矩形的 4 条线段中的任何一条线段之间的交点。 归属地: 此函数改编自 Paul Bourke 的有用 treatice on intersections .

这里是示例代码和演示,展示了如何在障碍物的碰撞点停止播放器:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
    var BB=canvas.getBoundingClientRect();
    offsetX=BB.left;
    offsetY=BB.top;        
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }

var isDown=false;
var startX,startY,dragging;

ctx.translate(0.50,0.50);
ctx.textAlign='center';
ctx.textBaseline='middle';

var pts;
var p1={x:50,y:50,w:25,h:25,fill:''};
var p2={x:250,y:250,w:25,h:25,fill:''};
var ob={x:100,y:150,w:125,h:25,fill:''};
var obVertices=[
    {x:ob.x,y:ob.y},
    {x:ob.x+ob.w,y:ob.y},
    {x:ob.x+ob.w,y:ob.y+ob.h},
    {x:ob.x,y:ob.y+ob.h}
];
var s1,s2,s3,e1,e2,e3,o1,o2,o3,o4;

draw();

$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUpOut(e);});
$("#canvas").mouseout(function(e){handleMouseUpOut(e);});


function draw(){
    ctx.clearRect(0,0,cw,ch);
    //
    ctx.lineWidth=4;
    ctx.globalAlpha=0.250;
    ctx.strokeStyle='blue';
    ctx.strokeRect(ob.x,ob.y,ob.w,ob.h);
    ctx.globalAlpha=1.00;
    ctx.fillStyle='black';
    ctx.fillText('obstacle',ob.x+ob.w/2,ob.y+ob.h/2);
    //
    ctx.globalAlpha=0.250;
    ctx.strokeStyle='gold';
    ctx.strokeRect(p1.x,p1.y,p1.w,p1.h);
    ctx.strokeStyle='purple';
    ctx.strokeRect(p2.x,p2.y,p2.w,p2.h);
    ctx.fillStyle='black';
    ctx.globalAlpha=1.00;
    ctx.fillText('start',p1.x+p1.w/2,p1.y+p1.h/2);
    ctx.fillText('end',p2.x+p2.w/2,p2.y+p2.h/2);
}


function handleMouseDown(e){
  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();
  
  startX=parseInt(e.clientX-offsetX);
  startY=parseInt(e.clientY-offsetY);

  // Put your mousedown stuff here
  var mx=startX;
  var my=startY;
  if(mx>p1.x && mx<p1.x+p1.w && my>p1.y && my<p1.y+p1.h){
      isDown=true;
      dragging=p1;
  }else if(mx>p2.x && mx<p2.x+p2.w && my>p2.y && my<p2.y+p2.h){
      isDown=true;
      dragging=p2;
  }
}

function handleMouseUpOut(e){
  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();
  // Put your mouseup stuff here
  isDown=false;
  dragging=null;
}

function handleMouseMove(e){
  if(!isDown){return;}
  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();

  mouseX=parseInt(e.clientX-offsetX);
  mouseY=parseInt(e.clientY-offsetY);

  // Put your mousemove stuff here
  var dx=mouseX-startX;
  var dy=mouseY-startY;
  startX=mouseX;
  startY=mouseY;
  //
  dragging.x+=dx;
  dragging.y+=dy;
  //
  draw();
  //
  setPlayerVertices(p1,p2);
  var c=hasCollided(obVertices);
  if(c.dx){
      ctx.strokeStyle='gold';
      ctx.strokeRect(p1.x+c.dx,p1.y+c.dy,p1.w,p1.h);
      ctx.fillStyle='black';
      ctx.fillText('hit',p1.x+c.dx+p1.w/2,p1.y+c.dy+p1.h/2);
      line(c.s,c.i,'red');
  }
}

function setPlayerVertices(p1,p2){
    var tl1={x:p1.x,      y:p1.y};
    var tl2={x:p2.x,      y:p2.y};
    var tr1={x:p1.x+p1.w, y:p1.y};
    var tr2={x:p2.x+p2.w, y:p2.y};
    var br1={x:p1.x+p1.w, y:p1.y+p1.h};
    var br2={x:p2.x+p2.w, y:p2.y+p2.h};
    var bl1={x:p1.x,      y:p1.y+p1.h};
    var bl2={x:p2.x,      y:p2.y+p2.h};
    //
    if(p1.x<=p2.x && p1.y<=p2.y){
        s1=tr1; s2=br1; s3=bl1;
        e1=tr2; e2=br2; e3=bl2;
        o1=0; o2=1; o3=3; o4=0;
    }else if(p1.x<=p2.x && p1.y>=p2.y){
        s1=tl1; s2=tr1; s3=br1;
        e1=tl2; e2=tr2; e3=br2;
        o1=2; o2=3; o3=3; o4=0;
    }else if(p1.x>=p2.x && p1.y<=p2.y){
        s1=tl1; s2=br1; s3=bl1;
        e1=tl2; e2=br2; e3=bl2;
        o1=0; o2=1; o3=1; o4=2;
    }else if(p1.x>=p2.x && p1.y>=p2.y){
        s1=tl1; s2=tr1; s3=bl1;
        e1=tl2; e2=tr2; e3=bl2;
        o1=1; o2=2; o3=2; o4=3;
    }
}

function hasCollided(o){
    //
    var i1=line2lineIntersection(s1,e1,o[o1],o[o2]);
    var i2=line2lineIntersection(s2,e2,o[o1],o[o2]);
    var i3=line2lineIntersection(s3,e3,o[o1],o[o2]);
    var i4=line2lineIntersection(s1,e1,o[o3],o[o4]);
    var i5=line2lineIntersection(s2,e2,o[o3],o[o4]);
    var i6=line2lineIntersection(s3,e3,o[o3],o[o4]);
    //
    var tracks=[];
    if(i1){tracks.push(track(s1,e1,i1));}
    if(i2){tracks.push(track(s2,e2,i2));}
    if(i3){tracks.push(track(s3,e3,i3));}
    if(i4){tracks.push(track(s1,e1,i4));}
    if(i5){tracks.push(track(s2,e2,i5));}
    if(i6){tracks.push(track(s3,e3,i6));}
    //
    var nohitDist=10000000;
    var minDistSq=nohitDist;
    var halt={dx:null,dy:null,};
    for(var i=0;i<tracks.length;i++){
        var t=tracks[i];
        var testdist=t.dx*t.dx+t.dy*t.dy;
        if(testdist<minDistSq){
            minDistSq=testdist;
            halt.dx=t.dx;
            halt.dy=t.dy;
            halt.s=t.s;
            halt.i=t.i;
        }
    }
    return(halt);
}
//
function track(s,e,i){
    dot(s);dot(i);line(s,i);line(i,e);
    return({ dx:i.x-s.x, dy:i.y-s.y, s:s, i:i });
}


function line2lineIntersection(p0,p1,p2,p3) {
    var unknownA = (p3.x-p2.x) * (p0.y-p2.y) - (p3.y-p2.y) * (p0.x-p2.x);
    var unknownB = (p1.x-p0.x) * (p0.y-p2.y) - (p1.y-p0.y) * (p0.x-p2.x);
    var denominator  = (p3.y-p2.y) * (p1.x-p0.x) - (p3.x-p2.x) * (p1.y-p0.y);        
    // Test if Coincident
    // If the denominator and numerator for the ua and ub are 0
    //    then the two lines are coincident.    
    if(unknownA==0 && unknownB==0 && denominator==0){return(null);}
    // Test if Parallel 
    // If the denominator for the equations for ua and ub is 0
    //     then the two lines are parallel. 
    if (denominator == 0) return null;
    // If the intersection of line segments is required 
    // then it is only necessary to test if ua and ub lie between 0 and 1.
    // Whichever one lies within that range then the corresponding
    // line segment contains the intersection point. 
    // If both lie within the range of 0 to 1 then 
    // the intersection point is within both line segments. 
    unknownA /= denominator;
    unknownB /= denominator;
    var isIntersecting=(unknownA>=0 && unknownA<=1 && unknownB>=0 && unknownB<=1)
    if(!isIntersecting){return(null);}
    return({
        x: p0.x + unknownA * (p1.x-p0.x),
        y: p0.y + unknownA * (p1.y-p0.y)
    });
}

function dot(pt){
    ctx.beginPath();
    ctx.arc(pt.x,pt.y,3,0,Math.PI*2);
    ctx.closePath();
    ctx.fill();
}

function line(p0,p1,stroke,lw){
    ctx.beginPath();
    ctx.moveTo(p0.x,p0.y);
    ctx.lineTo(p1.x,p1.y);
    ctx.lineWidth=lw || 1;
    ctx.strokeStyle=stroke || 'gray';
    ctx.stroke();
}
body{ background-color: ivory; }
#canvas{border:1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Drag start & end player position rects<br>The shortest segment intersecting the obstacle is red.<br>The repositioned player is shown on the obstacle.</h4>
<canvas id="canvas" width=400 height=400></canvas>

关于javascript - 如何在 Canvas 中创建障碍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34607871/

有关javascript - 如何在 Canvas 中创建障碍的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  3. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  4. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  5. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  6. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  7. ruby - 如何在 Lion 上安装 Xcode 4.6,需要用 RVM 升级 ruby - 2

    我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121

  8. ruby-on-rails - 如何在 ruby​​ 交互式 shell 中有多行? - 2

    这可能是个愚蠢的问题。但是,我是一个新手......你怎么能在交互式ruby​​shell中有多行代码?好像你只能有一条长线。按回车键运行代码。无论如何我可以在不运行代码的情况下跳到下一行吗?再次抱歉,如果这是一个愚蠢的问题。谢谢。 最佳答案 这是一个例子:2.1.2:053>a=1=>12.1.2:054>b=2=>22.1.2:055>a+b=>32.1.2:056>ifa>b#Thecode‘if..."startsthedefinitionoftheconditionalstatement.2.1.2:057?>puts"f

  9. ruby-on-rails - 如何在我的 Rails 应用程序 View 中打印 ruby​​ 变量的内容? - 2

    我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby​​中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R

  10. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser

随机推荐