Hi everyone,
I want to create a fake touch on the screen using Cocos Creator 3.8. Before in cocos2dx, I am using cc.eventManager.dispatchevent(begintouch) and cc.eventManager.dispatchevent(endtouch) to create a fake touch with a given position.
I am trying to do similar in Creator 3.8, but it won’t give me the same result.
Here is my implement, I am not sure I am doing it correctly or I am missing anything. Please suggest. Thank you.
public fakeTouch(x: number, y: number)
{
const touches: Touch = ;
const temp = this.getFakeTouch(x, y);
touches.push(temp);
const touchBeginEvent = new EventTouch(touches, false, Node.EventType.TOUCH_START);
director.getScene()?.dispatchEvent(touchBeginEvent);
const touchEvent = new EventTouch(touches, false, Node.EventType.TOUCH_END);
director.getScene()?.dispatchEvent(touchEvent);
}
protected getFakeTouch(x: number, y: number) {
const touch = new Touch(x,y);
touch.setPrevPoint(x, y);
return touch;
}
May I know what is this for? What is your use case?
I am trying to create an auto test, where I can fake a random touch on screen to trigger a function.
This is how I did it in the past. Please note that I think the ClickLocation isnt needed anymore this was two past scripts I put together.
updateScreenPosition(event: EventMouse | EventTouch) {
if (event instanceof EventMouse) {
this.screenPosition.set(event.getUILocationX(), event.getUILocationY(), 0);
} else {
const touch = event.getTouches()[0];
if (!this.firstTouch) {
this.firstTouch = touch;
}
if (touch && touch.getID() === this.firstTouch.getID()) {
this.screenPosition.set(touch.getUILocationX(), touch.getUILocationY(), 0);
}
}
this.lastMousePosition.set(this.screenPosition.x, this.screenPosition.y);
}
let clickLocation = new Vec2(this.lastMousePosition.x, this.lastMousePosition.y)
clickLocation.x -= view.getVisibleSize().width / 2;
clickLocation.y -= view.getVisibleSize().height / 2;
let clickEvent = new EventMouse(Input.EventType.MOUSE_DOWN, true);
clickEvent.setLocation(clickLocation.x, clickLocation.y);
collider.node.getComponent(RigidBody2D).node.dispatchEvent(clickEvent);