Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我如何控制我的对象';javascript中通过鼠标的方向?_Javascript_Html - Fatal编程技术网

我如何控制我的对象';javascript中通过鼠标的方向?

我如何控制我的对象';javascript中通过鼠标的方向?,javascript,html,Javascript,Html,我正在做一个html5游戏项目。在这种情况下,我必须通过鼠标控制我的对象方向。我已经用键盘控制了它。但我想实现鼠标控制。因此,任何人都可以帮助回复我。使用“onmousemove”并捕获其事件 window.onmousemove = functionName; functionName(event){ //now read the relevant event properties for the mouse //console.log(event); //use conso

我正在做一个html5游戏项目。在这种情况下,我必须通过鼠标控制我的对象方向。我已经用键盘控制了它。但我想实现鼠标控制。因此,任何人都可以帮助回复我。

使用“onmousemove”并捕获其事件

window.onmousemove = functionName;

functionName(event){
    //now read the relevant event properties for the mouse
    //console.log(event); //use console.log to get a list of possible event properties
    x = event.pageX;
    y = event.pageY;

}
您需要跟踪以前的位置,并在该功能中执行许多其他操作,但是有很多文档可以帮助您开始

请尝试以下链接:
以下代码可能会给您一些想法

var refPos = {x:window.event.clientX,y:window.event.clientY};

window.addEventListener("mousemove",function(){
var curPos = {x:window.event.clientX,y:window.event.clientY};
var left = refPos.x - curPos.x;
var top = refPos.y - curPos.y;
var direction = "";
direction += (top < 0)?"South":"North";
direction += (left <0)?"East":"West";
alert("Relative Direction " + direction);
},true);
var refPos={x:window.event.clientX,y:window.event.clientY};
addEventListener(“mousemove”,function()){
var curPos={x:window.event.clientX,y:window.event.clientY};
左侧变量=参考位置x-当前位置x;
var top=参考位置y-当前位置y;
var方向=”;
方向+=(顶部<0)?“南”:“北”;

方向+=(左假设您使用的是jQuery:

$(document).bind('mousemove', function(e) {
    var refObj = $('#image-id');  // reference object selector
    var objPos = refObj.offset(); // get object's absolute position
    var objCenterPos = {          // get object's center absolute position
        x: objPos.left + refObj.width()  / 2,
        y: opjPos.top  + refObj.height() / 2
    };
    var refPos = { // compute mouse position relative to reference object
        x: e.pageX - objCenterPos.x,
        y: e.pageY - objCenterPos.y
    };

    updateDirectionVector(refPos); // refPos is also the direction vector
});

function updateDirectionVector(vector) {
    // do whatever you want here
}

您使用的是框架吗?jQuery等?