【Unity】Version 1 ショットガンから球を発射
Version 1. ショットガンから球を発射。
Assetsストアから「Survival Shooter Tutorial」素材を使ってお勉強中!
環境メモ
⭐️Mac OS Mojave バージョン10.14
⭐️Unity 2018.2.15f1
実際に動かした動画はこちら↓↓
https://twitter.com/nonnonkapibara/status/1065776198347710464
1.Assetsストアから「Survival Shooter Tutorial」ダウンロードする
https://assetstore.unity.com/packages/essentials/tutorial-projects/survival-shooter-tutorial-40756
2.「Floor」をDrag&Dropで配置する
3.「Floor」を中心に配置する
4.「Player」を「Main Camera」の直下に配置する
Player -> PlayerGunに名前を変更する。
Survival Shooter TutorialにPlayerのキャラクターがなかったら
↑Player.fbx
ダウンローする
5.作業するために、一旦、キャラクター(Player)のみを非表示にする
6.球を作る Sphereを選択して、名前を「Bullet」にする
7.球をPrefabにする。Purefabにしたら、元のBulletは削除する
8.「ShooterScript」を作成し、PlayerGunに、配置する
9.bulletを選択しRigidbodyを追加する。
Use GravityのチェックをOFFにする。重力の影響を受けない。
10.bulletにスクリプトを追加する
11.BulletにDestroyScriptを追加する
■ShooterScript.cs
>|cs|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShooterScript : MonoBehaviour {
// 銃弾
[SerializeField] GameObject bulletPrefab = null;
// 銃口
[SerializeField] Transform ganPoint = null;
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown("space"))
{
Createbullet();
}
}
private void Createbullet()
{
// 銃弾を生成する
if (bulletPrefab != null && ganPoint != null) {
Instantiate(bulletPrefab, ganPoint.position, ganPoint.rotation);
}
}
}
||<
■BulletScript.cs
>|cs|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class BulletScript : MonoBehaviour {
//RequireComponentは、アタッチし忘れを防ぐ。ここではRigidbodyは必須。
// 球のスピード
[SerializeField] float spped = 10f;
void Start () {
// 速度
var velocity = spped * transform.forward;
var rigid = GetComponent<Rigidbody>();
// AddForceはrigidbodyへの継続的な力を追加
// VelocityChangはrigidbodyに瞬時に速度変化を追加
rigid.AddForce(velocity, ForceMode.VelocityChange);
}
}
||<
■DestroyScript.cs
>|cs|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyScript : MonoBehaviour {
[SerializeField] float life = 1f;
void Start () {
// 球のゲームオブジェクトを破棄する
Destroy(gameObject, life);
}
}
||<