物体に力を与える方法を学ぶ

ピンボールとか作るときにボールに力を加えたい。

そこで力を与える方法を学ぶ。

RigidBodyを動かす方法としてAddforceを使う方法があるらしい。

https://nekopro99.com/move-rigidbody-addforce/

 上記のサイトを参考にした。

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class Upper : MonoBehaviour
  5. {
  6.     // Rigidbodyコンポーネントを入れる変数"rb"を宣言する。
  7.     public Rigidbody rb;
  8.     void Start()
  9.     {
  10.         // Rigidbodyコンポーネントを取得する
  11.         rb = GetComponent<Rigidbody>();
  12.     }
  13.     void FixedUpdate()
  14.     {
  15.         // Upキーで前に進む
  16.         if (Input.GetKey("up"))
  17.         {
  18.             rb.AddForce(0,10f,0, ForceMode.Impulse);
  19.         }
  20.     }
  21. }

 参考サイトを基に力の方向を変えてみた。

これはupキーを押したらyの方向に10フォース加える。

後ろのフォースモードで力の加え方をいろいろ調整ができる。

 

そして力の調節は前回使用したマウスのドラッグ距離を利用した。

 

sashimimayonezu.hatenablog.com

 

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class Upper : MonoBehaviour
  5. {
  6.     // Rigidbodyコンポーネントを入れる変数"rb"を宣言する。
  7.     public Rigidbody rb;
  8.     float speed;
  9.     Vector3 startPos;
  10.     void Start()
  11.     {
  12.         speed = 0;
  13.         // Rigidbodyコンポーネントを取得する
  14.         rb = GetComponent<Rigidbody>();
  15.     }
  16.     void Update()
  17.     {
  18.         // Upキーで前に進む
  19.         if (Input.GetMouseButtonDown(0))
  20.         {
  21.             this.startPos = Input.mousePosition;
  22.         }
  23.         else if (Input.GetMouseButtonUp(0))
  24.         {
  25.             Vector3 endPos = Input.mousePosition;
  26.             float swipelength = endPos.y - startPos.y;
  27.             this.speed = -swipelength / 5000.0f;
  28.             if (this.speed >= 0.1f)
  29.             {
  30.                 this.speed = 0.1f;
  31.             }
  32.             if (this.speed <= -0.1f)
  33.             {
  34.                 this.speed = -0.1f;
  35.             }
  36.             Debug.Log(this.speed);
  37.         }
  38.         rb.AddForce(0, this.speed*300, 0, ForceMode.Force);
  39.         this.speed *= 0.99f;
  40.     }
  41. }

 これによって下に引っ張るようにドラッグしたら

上に吹っ飛ぶようになった。

これで雑なスマートボールが完成した。

f:id:sashimimayonezu:20200818185200g:plain

丁寧にガワを作ってあげたらちょっとはましになるかも

今日はここまで

 

https://help.hatenablog.com/entry/developer-option?_gl=1*ojnx55*_gcl_au*NzA5NzY1Mzc3LjE3MTA2NTgyODA.