gpt4 book ai didi

javascript - 如何使用 KineticJS 检测可拖动圆形何时与另一个圆形重叠?

转载 作者:行者123 更新时间:2023-11-30 13:06:11 24 4
gpt4 key购买 nike

我有一个可拖动的圆形,用户可以将其拖动到另一个圆形 [静态,不可拖动]。当可拖动圆圈与静态圆圈重叠时,我需要显示“成功”文本。我该怎么做?

最佳答案

当用户拖动圆圈时,您可以处理“dragmove”事件。

在“dragmove”中:测试圆圈是否发生碰撞。如果是,则宣告成功!

Circle1.on("dragmove",function(){
if(theyAreColliding(Circle1,Circle2)){
// Success!
}
});

碰撞测试如下所示:

function theyAreColliding(c1,c2){
var dx=c1.getX()-c2.getX();
var dy=c1.getY()-c2.getY();
var radiiSum=c1.getRadius()+c2.getRadius();
console.log(dx+"/"+dy+": "+radiiSum);
return((dx*dx+dy*dy)<radiiSum*radiiSum);
}

这是代码和 fiddle :http://jsfiddle.net/m1erickson/3dQpL/

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Prototype</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.3.3-beta.js"></script>

<style>
canvas{
border:solid 1px #ccc;
}
</style>
<script>
$(function(){

var layer = new Kinetic.Layer();
var stage = new Kinetic.Stage({
container: "container",
width: 400,
height: 400
});
stage.add(layer);

// mouse events don't fire on the empty part of the stage
// so fill the stage with a rect to get events on entire stage
// now stage.on("mouse... will work
var background = new Kinetic.Rect({
x: 0,
y: 0,
width: 400, //stage.getWidth(),
height: 400, //stage.getHeight(),
fill: "#eee"
});
layer.add(background);

var Radius1=50;
var Circle1=new Kinetic.Circle({
x: 225,
y: 125,
radius: Radius1,
fill: 'green',
stroke: 'orange',
strokeWidth: 2,
draggable:true
});
layer.add(Circle1);


var Radius2=50;
var Circle2=new Kinetic.Circle({
x: 75,
y: 175,
radius: Radius2,
fill: 'blue',
stroke: 'black',
strokeWidth: 2
});
layer.add(Circle2);

var message = new Kinetic.Text({
x: 10,
y: 15,
text: "",
fontSize: 30,
fontFamily: 'Calibri',
fill: 'green'
});
layer.add(message);

var instructions = new Kinetic.Text({
x: 10,
y: 285,
text: "Drag green on top of blue",
fontSize: 18,
fontFamily: 'Calibri',
fill: 'green'
});
layer.add(instructions);
layer.draw();

Circle1.on("dragmove",function(){
if(theyAreColliding(Circle1,Circle2)){
message.setText("Collision Detected!");
Circle1.setFill("red");
layer.draw();
}else{
}
});


function theyAreColliding(c1,c2){
var dx=c1.getX()-c2.getX();
var dy=c1.getY()-c2.getY();
var radiiSum=c1.getRadius()+c2.getRadius();
console.log(dx+"/"+dy+": "+radiiSum);
return((dx*dx+dy*dy)<radiiSum*radiiSum);
}



}); // end $(function(){});

</script>
</head>

<body>
<div id="container"></div>
</body>
</html>

关于javascript - 如何使用 KineticJS 检测可拖动圆形何时与另一个圆形重叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15628278/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com