Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

348
Visualizações
Randomly generate += or -= javascript

Hi i am trying to assign either += or -= to an object position. Firstly I have random math choosing a number:

var min = 9;
 var max = 11;
 var pos = Math.floor(Math.random() * (max - min + 1)) + min;

I am trying to add the out come of pos to this._target.position.z and this._target.position.x but I want it to be randomly either added or subtracted

so the random out come should be for the Z position should be either:

this._target.position.z += pos;

or

this._target.position.z -= pos;

and then for the X position should be either:

this._target.position.x += pos;

or

this._target.position.x -= pos;

thanks in advance.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If you want to randomly do x += value or x -= value you can simply use the first version, and then multiply your value by -1 if you want to do a -=.

In other words:

const isNegative = // however you determine this, eg. Math.random
const newValue += (isNegative ? -1 : 1) * value;

Or, to apply it back to your case, using @Chris G's suggestion in the comments:

 const oneOrNegativeOne = (Math.floor(Math.random() * 2) * 2 - 1);
 this._target.position.x += oneOrNegativeOne * pos;
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use a condition based on a random event like this :

if (Math.floor(Math.random() * 2)) {
    //the condition return 0 or 1 for false or true
    this._target.position.z += pos;
} else {
    this._target.position.z -= pos;
}

and either for this._target.position.x

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda