ピンボールとか作るときにボールに力を加えたい。
そこで力を与える方法を学ぶ。
RigidBodyを動かす方法としてAddforceを使う方法があるらしい。
上記のサイトを参考にした。
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Upper : MonoBehaviour
- {
- // Rigidbodyコンポーネントを入れる変数"rb"を宣言する。
- public Rigidbody rb;
- void Start()
- {
- // Rigidbodyコンポーネントを取得する
- rb = GetComponent<Rigidbody>();
- }
- void FixedUpdate()
- {
- // Upキーで前に進む
- if (Input.GetKey("up"))
- {
- rb.AddForce(0,10f,0, ForceMode.Impulse);
- }
- }
- }
参考サイトを基に力の方向を変えてみた。
これはupキーを押したらyの方向に10フォース加える。
後ろのフォースモードで力の加え方をいろいろ調整ができる。
そして力の調節は前回使用したマウスのドラッグ距離を利用した。
sashimimayonezu.hatenablog.com
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Upper : MonoBehaviour
- {
- // Rigidbodyコンポーネントを入れる変数"rb"を宣言する。
- public Rigidbody rb;
- float speed;
- Vector3 startPos;
- void Start()
- {
- speed = 0;
- // Rigidbodyコンポーネントを取得する
- rb = GetComponent<Rigidbody>();
- }
- void Update()
- {
- // Upキーで前に進む
- if (Input.GetMouseButtonDown(0))
- {
- this.startPos = Input.mousePosition;
- }
- else if (Input.GetMouseButtonUp(0))
- {
- Vector3 endPos = Input.mousePosition;
- float swipelength = endPos.y - startPos.y;
- this.speed = -swipelength / 5000.0f;
- if (this.speed >= 0.1f)
- {
- this.speed = 0.1f;
- }
- if (this.speed <= -0.1f)
- {
- this.speed = -0.1f;
- }
- Debug.Log(this.speed);
- }
- rb.AddForce(0, this.speed*300, 0, ForceMode.Force);
- this.speed *= 0.99f;
- }
- }
これによって下に引っ張るようにドラッグしたら
上に吹っ飛ぶようになった。
これで雑なスマートボールが完成した。
丁寧にガワを作ってあげたらちょっとはましになるかも
今日はここまで