Individual Unit selection in RTS games

Individual Unit selection in RTS games

Problem Description:

In most RTS games only ONE unit can be active at a time (of course, if you don`t use a selection box over multiple units). So, if you select the second unit, the first one is deselected automatically. How is it possible to achieve in JavaScript?

`

function knightMove(){
    console.log("I move");    
}


function riderMove(){
    console.log("I move too");    
}


let knight = document.querySelector(".knight");
let rider = document.querySelector(".rider");


// UNIT SELECTION
function select(unit,funct1){
    unit.addEventListener("click",selectedUnit);
    function selectedUnit(){
    window.addEventListener("keydown",funct1);
    unit.style.boxShadow = "0 0 44px 22px red";
    console.log(name, "IS SELECTED");
    // DESELECT IF BACKGROUND IS CLICKED
    bg.addEventListener("click",()=>{
        window.removeEventListener("keydown",funct1);
        unit.style.boxShadow = "0 0 44px 22px white";
        console.log(name, "IS DESELECTED");
    })
    }
}

select(knight,knightMove);
select(rider,riderMove);

`

Solution – 1

The simplest way would be to store the one selected unit as a global variable.

Then you can simply add and remove a CSS class as necessary

const knight = document.querySelector('.knight');
const rider = document.querySelector('.rider');
let selectedUnit = null;

for (const unit of [knight, rider]) unit.addEventListener('click', selectUnit);
document.addEventListener('click', deselectCurrentUnit);

function deselectCurrentUnit(){
  if (selectedUnit) selectedUnit.classList.remove('selected');
}

function selectUnit(event) {
  event.stopPropagation();
  deselectCurrentUnit();
  const unit = event.target;
  selectedUnit = unit;
  unit.classList.add('selected');
}
body {
  background: green;
}

.unit {
  cursor: pointer;
  margin: 50px;
  box-shadow: 0 0 44px 22px white;
}

.selected {
  box-shadow: 0 0 44px 22px red;
}
  <p class="knight unit">Knight</p>
  <p class="rider unit">Rider</p>
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject