Outerra forum

Please login or register.

Login with username, password and session length
Advanced search  

News:

Outerra Tech Demo download. Help with graphics driver issues

Author Topic: EvantHandlers  (Read 8803 times)

SteelRat

  • Sr. Member
  • ****
  • Posts: 380
  • newbie
EvantHandlers
« on: September 30, 2015, 11:49:32 am »

Hi cameni!

I really liked this event handler
Code: [Select]
this.register_axis()It provides opportunities for creativity, and I once again have to use it instead
Code: [Select]
this.register_event()
That's why, let's say there is a handler
Code: [Select]
this.register_axis("car/CARsim/all_wheels", {minval:0, maxval:1, center:0, vel:1000, acc:1000}, function(v) {
      if (Math.round(this.speed()) == 0) this.tm.allWheels = v;
}, 0);

Let the vehicle travels during a call event, it is natural to the user action will not be taken by itself is not terrible)

BUT !!!
Counter "v" has changed its meaning, that in the future will cause not the correct effect.

And use this handler like)
Logged

SteelRat

  • Sr. Member
  • ****
  • Posts: 380
  • newbie
Re: EvantHandlers
« Reply #1 on: September 30, 2015, 02:56:40 pm »

Hi cameni!

How to make a "reset" the two axes of one button?
Since working with only one axle.

Code: [Select]
this.register_axis("car/CARsim/view_cabin_cam_move", {minval:0, maxval:0.45, center:0, vel:2, acc:2}, function(v) {
   this.player.moveCamPos.y = v;
   this.player.moveCam = 1;
}, 0);

this.register_axis("car/CARsim/view_cabin_cam_strafe", {minval:-0.3, maxval:0.3, center:0, vel:2, acc:2}, function(v) {
   this.player.moveCamPos.x = v;
   this.player.moveCam = 1;
}, 0);

Code: [Select]
{
    "name": "view_cabin_cam_move",

    "comment": "View: Move the camera forward/backward",

    "important": true,

    "bindings": [
         {

            "event_name": "Num8",
            "mode": "toggle+"
         },
         {

            "event_name": "Num2",
            "mode": "toggle-"

         },
         {
            "event_name": "Num5",

            "mode": "reset"
         }

     ]

},
{

     "name": "view_cabin_cam_strafe",

     "comment": "View: Move the camera left/right",
     "important": true,
     "bindings": [

         {

             "event_name": "Num4",

             "mode": "toggle-"

         },

         {
             "event_name": "Num6",

             "mode": "toggle+"

         },

         {

             "event_name": "Num5",
             "mode": "reset"
         }

     ]

}
Logged

cameni

  • Brano Kemen
  • Outerra Administrator
  • Hero Member
  • *****
  • Posts: 6721
  • No sense of urgency.
    • outerra.com
Re: EvantHandlers
« Reply #2 on: September 30, 2015, 04:09:18 pm »

BUT !!!
Counter "v" has changed its meaning, that in the future will cause not the correct effect.

You mean it changed meaning between register_event and register_axis? I don't know what you mean by "in the future will cause not the correct effect".

Quote
How to make a "reset" the two axes of one button?

You mean how to use one button to reset two separate axes at once? It's not possible with a simple binding in two actions, you would have to create a third action that you'd bind as register_event and reset both values there. But ideally that needs ability to access the other actions to reset or set their values, and that's not currently possible ...
Logged

SteelRat

  • Sr. Member
  • ****
  • Posts: 380
  • newbie
Re: EvantHandlers
« Reply #3 on: September 30, 2015, 05:28:17 pm »

Quote
You mean it changed meaning between register_event and register_axis? I don't know what you mean by "in the future will cause not the correct effect".

RU
Я не имел ввиду каких либо глобальных проблем, я рассуждаю о пользовательском уровне.

Например я создаю подобный обработчик события
Code: [Select]
this.register_axis("car/CARsim/all_wheels", {minval:0, maxval:1, center:0, vel:1000, acc:1000}, function(v) {
      if (Math.round(this.speed()) == 0) this.tm.allWheels = v;
}, 0);
В этом обработчике поставлено конкретное условие, при соблюдении которого изменения вступят в силу.
Начальное значение параметра V = 0.

Теперь представим такую ситуацию, пользователь во время движения автомобиля решил активировать ведущими все оси, естественно код в обработчике этого не позволит сделать, и не последует ни какого эффекта, автомобиль должен остановиться, что бы изменения вступили в силу. Само по себе это не проблема.
А проблема в том, что при следующем вызове этого события значение переданного в обработчик события параметра V будет равно 0, а не 1, так как предыдущий вызов хоть и не внёс ни каких изменений в логику автомобиля, но зато изменил значение V = 1.

Именно это я и имел ввиду.

И сначала я решил именно с этим обработчиком события связать взаимодействие с коробкой передач. Но когда дело дошло до автоматической коробки я понял, что использовать этот обработчик мне не получится, именно из за описанного выше эффекта.
И как раз из за того, чтобы переключить передачу на автомобиле с коробкой автомат, автомобиль не должен двигаться, и это условие пользователем может быть не соблюдено, в результате, начав играться с переключением передач на ходу, пользователь сведёт с ума логику). А у меня нет инструмента блокировать бестолковые выходки пользователя. Потому что у меня нет возможности дать указание не менять значение параметра V.

Может имеет смысл возвращать из функции обработчика результат обработки события TRUE или FALSE, и по результату уже принимать решение изменять значение параметра V, или оставить предыдущее значение.
Как здесь
Code: [Select]
function switch_seat(cam)
{
  if(cam===0)       //driver
    this.set_fps_camera_pos({x:-0.8,y:3.4,z:2.3});
  else if(cam===1)  //right seat
    this.set_fps_camera_pos({x:+0.8,y:3.4,z:2.3});
  else if(cam===2)  //wheel
    this.set_fps_camera_pos({x:-1.8,y:2.0,z:0.6});
  else
    return false;
  return true;
}
Logged

SteelRat

  • Sr. Member
  • ****
  • Posts: 380
  • newbie
Re: EvantHandlers
« Reply #4 on: September 30, 2015, 06:02:36 pm »

Quote
You mean how to use one button to reset two separate axes at once? It's not possible with a simple binding in two actions, you would have to create a third action that you'd bind as register_event and reset both values there. But ideally that needs ability to access the other actions to reset or set their values, and that's not currently possible ...

If I understand correctly, no.
OK. Thank.
Logged

cameni

  • Brano Kemen
  • Outerra Administrator
  • Hero Member
  • *****
  • Posts: 6721
  • No sense of urgency.
    • outerra.com
Re: EvantHandlers
« Reply #5 on: October 01, 2015, 01:56:07 am »

The event handler only signals what the user wanted to do. If he switched the controls but your conditions do not allow you to act immediately, then you have to implement this handling in the code. For example, you would set a variable indicating to switch, and then within the update_frame would check if it's set and if the conditions are met.
Logged

SteelRat

  • Sr. Member
  • ****
  • Posts: 380
  • newbie
Re: EvantHandlers
« Reply #6 on: October 01, 2015, 05:32:21 am »

The event handler only signals what the user wanted to do. If he switched the controls but your conditions do not allow you to act immediately, then you have to implement this handling in the code. For example, you would set a variable indicating to switch, and then within the update_frame would check if it's set and if the conditions are met.

Я это понимаю.
Для меня не проблема скорректировать в моём коде не желательное действие пользователя. Но вызов всё равно изменит текущее значение параметра V, например до вызова было V=0, после вызова стало V=1 даже если это действие не принято моим кодом. И я не могу сделать так, что бы следующий вызов события передал в функцию обработчика события снова V=1, так как предыдущее действие пользователя было не корректным.

Именно по этому мне и пришлось в нескольких случаях отказаться использовать этот обработчик события. А использовать его было очень полезно, так как этот обработчик позволят делать много разных настроек, что позволяет реализовывать разные полезные сценарии.
« Last Edit: October 01, 2015, 05:48:14 am by SteelRat »
Logged

cameni

  • Brano Kemen
  • Outerra Administrator
  • Hero Member
  • *****
  • Posts: 6721
  • No sense of urgency.
    • outerra.com
Re: EvantHandlers
« Reply #7 on: October 01, 2015, 05:58:52 am »

Но вызов всё равно изменит текущее значение параметра V, например до вызова было V=0, после вызова стало V=1 даже если это действие не принято моим кодом. И я не могу сделать так, что бы следующий вызов события передал в функцию обработчика события снова V=1, так как предыдущее действие пользователя было не корректным.

As I wrote, the meaning of the V parameter is the value of the switch as the user has set it, and it has to work with all input devices. Imagine that user binds this action to a joystick axis that does not return to zero, or to a physical toggle switch. We can't really prevent him from leaving the switch in the wrong position. In a real vehicle he would be physically impossible to move the switch to given position when the conditions aren't met.

If user currently binds the action to a joystick axis, we are unable to cancel his action.
But I get what you are saying in case of binding the action to keyboard or joystick buttons. You want to cancel the action if certain conditions aren't met, right? I'm not sure if this will be easy to implement, given the complex state handling, but I guess it could work for common cases. It could be handled like this:

Code: [Select]
this.register_axis("car/CARsim/all_wheels", {minval:0, maxval:1, center:0, vel:1000, acc:1000}, function(v) {
    var cond = Math.round(this.speed()) == 0;
    if(cond)
        this.tm.allWheels = v;
    return cond;    // returning false would cancel the internal state change
}, 0);
Logged

SteelRat

  • Sr. Member
  • ****
  • Posts: 380
  • newbie
Re: EvantHandlers
« Reply #8 on: October 01, 2015, 11:22:25 am »


Code: [Select]
this.register_axis("car/CARsim/all_wheels", {minval:0, maxval:1, center:0, vel:1000, acc:1000}, function(v) {
    var cond = Math.round(this.speed()) == 0;
    if(cond)
        this.tm.allWheels = v;
    return cond;    // returning false would cancel the internal state change
}, 0);

Да! Это то что я имею ввиду.
Если это возможно.
« Last Edit: October 01, 2015, 11:42:57 am by SteelRat »
Logged