# キー入力によるモーションの実行について

**URL:** <https://creatorsforum.live2d.com/t/topic/2581>\
**Category:** トラブル報告\
**Tags:** 使い方\
**Created:** [2024 年 5 月 13 日午前 12:26 UTC](https://creatorsforum.live2d.com/t/topic/2581 "2024-05-13T00:26:52Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![あぷぷ](https://avatars.discourse-cdn.com/v4/letter/%E3%81%82/8e8cbc/32.png) [@あぷぷ](https://creatorsforum.live2d.com/u/%E3%81%82%E3%81%B7%E3%81%B7)\
**Post date:** [2024 年 5 月 13 日午前 12:26 UTC](https://creatorsforum.live2d.com/t/topic/2581/1 "2024-05-13T00:26:52Z")

</div>

Cubism SDK For Web（5-r.1）で  
キー入力によりモーションを変更する方法を教えて頂きたく投稿させて頂きました。

SDKのデモコードを参考に  
Samples/TypeScript/Demo/src/lappdelegate.ts  
にキーボードイベント追加し、キー入力がはいればモーションを変更したいと考えているのですがうまくいきません。  
モーションを変更する以前に現在のモデルが取得できていません

onTap処理内を参考にしているのですが、  
this.\_models自体がundefinedになってしまており、  
新規でモデルを取得しようにもエラーになってしまいます

何が悪いのでしょう。。  
モーションの切り替え（実行）はstartMotionで良いのでしょうか。。

this.\_models.at(i).startMotion(LAppDefine.MotionGroupAdd, 0, LAppDefine.PriorityNormal);

```auto
window.addEventListener('keydown', onKeyDown);
function onKeyDown(e: KeyboardEvent): void {

  if (!LAppDelegate.getInstance()._view) {
      LAppPal.printMessage('view notfound');
      return;
  }

  if (e.key === "1") {

   console.log(this._models); // ← undefined
   this._models.set(0, null); // ← エラー
   this._models = this.getModel();// ← エラー

 //モーションの実行 これもエラー
 this._models.startMotion(LAppDefine.MotionGroupAdd, 0, LAppDefine.PriorityNormal);

     
  }
}

```

---

<div class="post-metadata">

**Author:** ![obs](https://avatars.discourse-cdn.com/v4/letter/o/c67d28/32.png) [@obs](https://creatorsforum.live2d.com/u/obs)\
**Post date:** [2024 年 5 月 13 日午前 1:12 UTC](https://creatorsforum.live2d.com/t/topic/2581/2 "2024-05-13T01:12:15Z")

</div>

こんにちは。

モデルのリストを保持するのはLAppLive2DManagerクラスです。  
なので以下のようにしてやるとモデルを取得できます。

```auto
LAppLive2DManager.getInstance().getModel(index);

```

全体としては以下のようなコードになるでしょう。

```auto
function onKeyDown(e: KeyboardEvent): void {
  if (e.key === '1') {
    const model = LAppLive2DManager.getInstance().getModel(0);
    console.log(model);

    // startMotion()でもOK
    model.startRandomMotion(
      LAppDefine.MotionGroupTapBody,
      LAppDefine.PriorityNormal,
      LAppLive2DManager.getInstance()._finishedMotion
    );
  }
}

```

---

<div class="post-metadata">

**Author:** ![あぷぷ](https://avatars.discourse-cdn.com/v4/letter/%E3%81%82/8e8cbc/32.png) [@あぷぷ](https://creatorsforum.live2d.com/u/%E3%81%82%E3%81%B7%E3%81%B7)\
**Post date:** [2024 年 5 月 13 日午前 1:33 UTC](https://creatorsforum.live2d.com/t/topic/2581/3 "2024-05-13T01:33:18Z")

</div>

さっそくのお返事ありがとうございます！  
無事実現することができました！助かりました！
