getHTMLElementPosition(element) {
var docElem = document.documentElement;
var leftOffset = window.pageXOffset - docElem.clientLeft;
var topOffset = window.pageYOffset - docElem.clientTop;
if (typeof element.getBoundingClientRect === 'function') {
var box = element.getBoundingClientRect();
return {
left: box.left + leftOffset,
top: box.top + topOffset,
width: box.width,
height: box.height
};
}
else {
if (element instanceof HTMLCanvasElement) {
return {
left: leftOffset,
top: topOffset,
width: element.width,
height: element.height
};
}
else {
return {
left: leftOffset,
top: topOffset,
width: parseInt(element.style.width),
height: parseInt(element.style.height)
};
}
}
}
// (x,y)世界坐标(左下角为0,0)
touchSimulation(x, y) {
let rect;
let inputManager = cc.internal.inputManager;
if (cc.sys.isBrowser) {
let canvas = document.getElementById("GameCanvas");
rect = this.getHTMLElementPosition(canvas);
} else {
rect = cc.view.getFrameSize();
rect.left = 0;
rect.top = 0;
}
let vp = cc.view.getViewportRect();
let sx = cc.view.getScaleX();
let sy = cc.view.getScaleY();
let ratio = cc.view.getDevicePixelRatio();
let htmlx = (x * sx + vp.x) / ratio + rect.left;
let htmly = rect.top + rect.height - (y * sy + vp.y) / ratio;
let pt = cc.v2(htmlx, htmly);
cc.log(`模拟点击坐标:${pt.x}, ${pt.y}`);
let touch = inputManager.getTouchByXY(pt.x, pt.y, rect);
inputManager.handleTouchesBegin([touch]);
setTimeout(() => {
inputManager.handleTouchesEnd([touch]);
}, 200);
}
网友评论