-
|
I want to make a game where the player can select multiple units, like in Starcraft (or the windows desktop, i guess), by clicking and dragging. However the way I have implemented has bad performance and it doesn't feel right. I have implemented most things as you would expect. On left mouse down, I store the position. On left mouse up I use that position and the stored position to make a square and flag all actors as selected if they are inside. There is probably a better way to do this using the collision system, but it's good enough for now. The problem is with the visual indicator. Which I implemented with the following pointer move listener. world.input.pointers.on("move", event => {
if (!this.selectionStart) {
return;
}
if (this.selection) {
this.selection.kill();
this.selection = undefined;
}
const currentMousePos = this.world.engine.screen.pageToWorldCoordinates(event.pagePos);
const pos = this.selectionStart.lerp(currentMousePos, 0.5);
const selectionWidth = Math.abs(currentMousePos.x - this.selectionStart.x);
const selectionHeight = Math.abs(currentMousePos.y - this.selectionStart.y);
this.selection = new Selection(pos, selectionWidth, selectionHeight);
this.world.add(this.selection);
});And this is the export class Selection extends Actor {
constructor(pos: Vector, width: number, height: number) {
super({
pos,
width,
height,
opacity: 0.15,
color: Color.Green,
});
}
}This does what I want. When you click down it creates a see-through square, where one corner is always at the position where you clicked down and the opposite corner is always where the pointer is. So, everytime the cursor moves it's killing an actor and creating a new one, which to me doesn't feel right, but I haven't made a lot of games so maybe that's the way to do it. However, this also has pretty bad performance. Moving your cursor around a little while selecting causes really bad lag. So my question is, is there a better way to do this? Is there a way to resize the selection object instead of killing it and creating a new one? Would that even matter for performance? Is the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
@YBStolker Great question!
I'd say your intuition is right on. Creating an
Totally! You should be able to re-use actors, this should help a lot with the lag by avoiding JavaScript garbage collection. The lerp function is very fast (roughly just an average). I've got some example code that I think improves the performance! Let me know if this helps |
Beta Was this translation helpful? Give feedback.
@YBStolker Great question!
I'd say your intuition is right on. Creating an
Actorevery time the move event fires is going to create a lot of actors that will need to be cleaned up. Try creating 1Selectionat the beginning of the game (or in theScene.onInitialize) and resizing it to match instead. You can adjust theisVisibleand the graphics.current.width and height of the default rectangle.