マウスを使って物体を動かす方法

マウスを使った物体の移動について学んでいく。

参考にしたサイト

 https://unity-shoshinsha.biz/archives/889

1、物体をマウスの位置に移動する

2.クリックで物体の動作をON/OFFにする。

3.クリックで物体に力を加える。

 f:id:sashimimayonezu:20200829211503g:plain

以下のスクリプトで次のことができる

 

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    //操作キャラの位置
    Vector3 playerPos;
    //向く方向
    Vector3 direction;
    Rigidbody rb;
    //スピード
    float speed = 0.03f;
    //ジャンプ力
    float thrust = 400;
    //移動できるかできないか
    bool moveOn;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        moveOn = true;
    }

    void Update()
    {
        //マウス右ボタンで移動できるかどうかを切り替え
        if (Input.GetMouseButtonDown(1))
        {
            moveOn = !moveOn;
        }

        //マウス中ボタンで時間止める
        if (Input.GetMouseButtonDown(2))
        {
            if (Time.timeScale != 0)
            {
                Time.timeScale = 0;
            }
            else
            {
                Time.timeScale = 1.0f;
            }
        }
    }

    void FixedUpdate()
    {
        //Raycastの情報を入れる
        RaycastHit hit;

        if (moveOn)
        {
            //カメラからマウスカーソルの位置に向けて出る
            //仮想の線に当たった場所に移動する
            if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),
                out hit, 100))
            {
                transform.position += transform.forward * speed;
            }

            //Raycastが当たった方向を操作キャラが向く
            playerPos = this.transform.position;
            direction = hit.point - playerPos;
            transform.rotation = Quaternion.LookRotation(new Vector3
                        (direction.x, 0, direction.z));

            //左クリックでジャンプする
            if (Input.GetMouseButtonDown(0))
            {
                rb.AddForce(transform.up * thrust);
            }
        }
    }
}

 4.マウスのドラッグで力を加える

以下過去の記事で書いた 

sashimimayonezu.hatenablog.com

 

f:id:sashimimayonezu:20200829213247g:plain

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class dragspeed : MonoBehaviour
{
    float speed = 0;
    Vector3 startPos;
    Vector3 endPos;
    // Start is called before the first frame update
    void Start()
    {
    }
    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            this.startPos = Input.mousePosition;
        }
        else if (Input.GetMouseButtonUp(0))
        {
            this.endPos = Input.mousePosition;
            float swipelength = endPos.x - startPos.x;
            this.speed = swipelength / 5000.0f;

        }
        transform.Translate(this.speed, 0, 0);
        this.speed *= 0.99f;
    }
}

 後以下のサイトについて勉強しておきたい

 https://gametukurikata.com/program/movetoclick

 

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