【Unity】画面跳ね返り

UnityはC#という言語で動いています。画面のふちで跳ね返るようにするためには範囲指定Mathf.Clamp関数を使います。

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

public class gamen : MonoBehaviour
{
   public float speed;

   void Start()
   {
       float x = Random.Range(-1.0f, 1.0f);
       float y = Random.Range(-1.0f, 1.0f);
       Vector3 velocity = new Vector3(x, y);
       velocity.Normalize();
       velocity *= speed;
       GetComponent<Rigidbody>().velocity = velocity;
   }

   

  
   void Update()
   {


       //対角線
       //Vector3 min = Camera.main.ViewportToWorldPoint(new Vector3(0,0,20));
       //Vector3 max = Camera.main.ViewportToWorldPoint(new Vector3(750,1334,20));

       Vector3 min = new Vector3(-5, -3.3f, -5);
       Vector3 max= new Vector3(5,10, 5);
       if (Input.GetKeyDown("space"))
       {
           Debug.Log(max);
           Debug.Log(min);

       }
   //豆腐場所
   Vector3 position = transform.position;
   Vector3 velocity = GetComponent<Rigidbody>().velocity;
   //プレイヤーの大きさ、そこまで必要じゃないかも
   float width = 1f;
   float height = 1f;

       if (position.x - width / 2.0f < min.x)
           {
               position.x = min.x + width / 2.0f;
               velocity.x *= -1.0f;
           }
           if (position.x + width / 2.0f > max.x)
           {
               position.x = max.x - width / 2.0f;
               velocity.x *= -1.0f;
           }
           if (position.y - height / 2.0f < min.y)
           {
               position.y = min.y + height / 2.0f;
               velocity.y *= -1.0f;
           }
           if (position.y + height / 2.0f > max.y)
           {
               position.y = max.y - height / 2.0f;
               velocity.y *= -1.0f;
           }
       if (position.z - width / 2.0f < min.z)
       {
           position.z = min.z + width / 2.0f;
           velocity.z *= -1.0f;
       }
       if (position.z + width / 2.0f > max.z)
       {
           position.z = max.z - width / 2.0f;
           velocity.z *= -1.0f;
       }
       transform.position = position;
           GetComponent<Rigidbody>().velocity = velocity;
       }

   
}

参考にしたサイト

http://win8kat.org/archives/1337
https://toburau.hatenablog.jp/entry/20160206/1454781364
https://uuc1h.hatenablog.jp/entry/2018/11/04/180036

上記のサイトのやり方だとエラーが多発したので、カメラのことや3Dの座標軸のことも併せて考慮しています。

参考にしたサイト

https://uni.gas.mixh.jp/unity/bounce.html                 http://tsubakit1.hateblo.jp/entry/2014/07/22/010739
https://ghoul-life.hatenablog.com/entry/2017/05/16/001743


app storeで自作ゲーム公開中〜
https://apps.apple.com/jp/app/%E8%B1%86%E8%85%90%E3%83%88%E3%83%A9%E3%83%B3%E3%83%9D%E3%83%AA%E3%83%B3/id1517071345


この記事が気に入ったらサポートをしてみませんか?