Add touch events

This commit is contained in:
Andras Schmelczer 2023-05-27 10:47:33 +01:00
parent bdc407b7df
commit f1808d5707
No known key found for this signature in database
GPG key ID: FC8F2C3D3D1A718C

View file

@ -74,15 +74,37 @@ export default class GameLoop {
window.addEventListener('resize', this.resize.bind(this)); window.addEventListener('resize', this.resize.bind(this));
canvas.addEventListener('mousemove', this.onSwipe.bind(this)); canvas.addEventListener('mousemove', this.onSwipe.bind(this));
canvas.addEventListener('touchmove', this.onSwipe.bind(this));
canvas.addEventListener('mousedown', (e) => { canvas.addEventListener('mousedown', (e) => {
this.brushPipeline.clearSwipes(); if (!this.isSwipeActive) {
this.isSwipeActive = true; this.brushPipeline.clearSwipes();
this.isSwipeActive = true;
}
this.onSwipe(e); this.onSwipe(e);
}); });
canvas.addEventListener('touchstart', (e) => {
if (!this.isSwipeActive) {
this.brushPipeline.clearSwipes();
this.isSwipeActive = true;
}
this.onSwipe(e);
});
window.addEventListener('mouseup', (e) => { window.addEventListener('mouseup', (e) => {
this.onSwipe(e); this.onSwipe(e);
this.isSwipeActive = false; this.isSwipeActive = false;
}); });
window.addEventListener('touchend', (e) => {
this.onSwipe(e);
this.isSwipeActive = false;
});
window.addEventListener('touchcancel', (e) => {
this.onSwipe(e);
this.isSwipeActive = false;
});
} }
public async start(): Promise<void> { public async start(): Promise<void> {
@ -107,14 +129,25 @@ export default class GameLoop {
return this.gameRules.generationCounts; return this.gameRules.generationCounts;
} }
private onSwipe(event: MouseEvent) { public get maxAgentCount(): number {
if (!this.isSwipeActive) { return this.agentGenerationPipeline.maxAgentCount;
}
private onSwipe(event: MouseEvent | TouchEvent) {
if (!this.isSwipeActive || !event) {
return; return;
} }
if (event instanceof TouchEvent && event.touches.length === 0) {
return;
}
const x = event instanceof MouseEvent ? event.clientX : event.touches[0].clientX;
const y = event instanceof MouseEvent ? event.clientY : event.touches[0].clientY;
const position = vec2.fromValues( const position = vec2.fromValues(
event.clientX * this.devicePixelRatio, x * this.devicePixelRatio,
this.canvas.height - event.clientY * this.devicePixelRatio this.canvas.height - y * this.devicePixelRatio
); );
this.brushPipeline.addSwipe(position); this.brushPipeline.addSwipe(position);
} }