code VR

Unity×VR(59)

スポンサーリンク

//tips

//攻撃モーション時の当たり判定

攻撃モーションの発生時間が短すぎて、ダメージ判定がシビアになっている問題を考える。

調べてみると、コライダーのIsTriggerのチェックを外しておいて、攻撃モーションの途中でチェックを入れ、攻撃モーションの終わりで再度チェックを外す方法とコライダーそのものをオフにしておき、攻撃モーション時にオンでコライダーをつけ判定を出し、Invokeで一定時間後にコライダーを外す方法がある。

今回は棒のコライダーを攻撃モーション時のみonにすることで対応させる。

private void Start()
{
m_Collider.enabled = false;
}

private void Update()
{
if (flag)
{
if (Input.GetKeyDown(KeyCode.Space))
{
anim = this.GetComponent<Animation>();
anim.Play();

//onAnim = true;

}

//onAnim = false;
}
}

public void HitStart()
{
m_Collider.enabled = true;
}

public void HitEnd()
{
m_Collider.enabled = false;
}

さらに、AnimationEventで、アニメーションの指定のタイミングでスクリプトの関数を呼ぶ。

Animation Eventをつけたアニメーションを含むAnimatorコンポーネントと同じオブジェクトにスクリプトをアタッチしないと関数を呼び出せない点に注意。

Event設定により無事アニメーション中にダメージ判定を行うことができるようになった。

次に、Playerであるcubeの向きの対応、棒を振るアニメーションの同期がされない場合があるなどのphotonシーンの問題を見ていく。

現在photonのGameplayerとして扱っているcubeには、playerタグとコライダー、photonviewコンポーネント、GamePlayerスクリプト、photonTransformview(position, rotation)、rigidbodyがついており、sceneスクリプトでGameObject Prefab = PhotonNetwork.Instantiate("GamePlayer", v, Quaternion.identity);の形で呼び出されている。

同名のprefabをresourceフォルダ下に作成していく。

動きに向きも追加するためGamePlayerスクリプトを編集する。また、向きをプレイヤーに追加したのでnamelabelには常にカメラの方へ向くスクリプトを添付する。

Namelabelは下記のスクリプトを添付して親オブジェクトの回転を無効化した。今回は3dtextを使用しており、UIではないのでこのようにしている点に注意。

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

public class DirectionController : MonoBehaviour
{
Vector3 def;

void Awake()
{
def = transform.localRotation.eulerAngles;
}

void Update()
{
Vector3 _parent = transform.parent.transform.localRotation.eulerAngles;
transform.localRotation = Quaternion.Euler(def - _parent);
}
}

Playerのスクリプトも下記のように変更したが、最初の立ち上がりのmoveが少し変なのでそこも調整する。

using Photon.Pun;
using Photon.Realtime;
using TMPro;
using UnityEngine;
using Hashtable = ExitGames.Client.Photon.Hashtable;

[RequireComponent(typeof(Renderer))]
public class GamePlayer : MonoBehaviourPunCallbacks
{
[SerializeField]
private TextMeshPro nameLabel = default;

private ProjectileManager projectileManager;
private Renderer spriteRenderer;

public Player Owner => photonView.Owner;

public Item item;

//move追加
public float speed = 2f; //プレイヤーの動くスピード

private Vector3 Player_pos; //プレイヤーのポジション
private Rigidbody rigd;

private void Awake()
{
projectileManager = GameObject.FindWithTag("ProjectileManager").GetComponent<ProjectileManager>();
spriteRenderer = GetComponent<Renderer>();

var gamePlayerManager = GameObject.FindWithTag("GamePlayerManager").GetComponent<GamePlayerManager>();
transform.SetParent(gamePlayerManager.transform);
}

private void Start()
{
PhotonNetwork.LocalPlayer.NickName = "Player";

var customProperties = photonView.Owner.CustomProperties;

// プレイヤー名の横にスコアを表示する
int score = photonView.Owner.GetScore();
nameLabel.text = $"{photonView.Owner.NickName}({score.ToString()})";

// 色相値が設定されていたら、スプライトの色を変化させる
if (photonView.Owner.TryGetHue(out float hue))
{
spriteRenderer.material.color = Color.HSVToRGB(hue, 1f, 1f);
}

Player_pos = GetComponent<Transform>().position; //最初の時点でのプレイヤーのポジションを取得
rigd = GetComponent<Rigidbody>(); //プレイヤーのRigidbodyを取得
}

private void Update()
{
if (photonView.IsMine)
{
//rotationにも対応

float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");

rigd.velocity = new Vector3(x * speed, 0, z * speed); //プレイヤーのRigidbodyに対してInputにspeedを掛けた値で更新し移動

Vector3 diff = transform.position - Player_pos; //プレイヤーがどの方向に進んでいるかがわかるように、初期位置と現在地の座標差分を取得

if (diff.magnitude > 0.01f) //ベクトルの長さが0.01fより大きい場合にプレイヤーの向きを変える処理を入れる
{
transform.rotation = Quaternion.LookRotation(diff); //ベクトルの情報をQuaternion.LookRotationに引き渡し回転量を取得しプレイヤーを回転させる
}

Player_pos = transform.position; //プレイヤーの位置を更新

/*
var direction = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")).normalized;
var dv = 6f * Time.deltaTime * direction;
//transform.Translate(dv.x, dv.y, 0f);
transform.Translate(dv.x, 0f, dv.y);
*/

if (Input.GetMouseButtonDown(0))
{
var playerWorldPosition = transform.position;
//var mouseWorldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 pos = Input.mousePosition;
pos.z = 10.0f;
Vector3 mouseWorldPosition = Camera.main.ScreenToWorldPoint(pos);

var dp = mouseWorldPosition - playerWorldPosition;
float angle = Mathf.Atan2(dp.y, dp.x);

// FireProjectile(angle)をRPCで実行する
//photonView.RPC(nameof(FireProjectile), RpcTarget.All, angle);

// 弾を発射するたびに弾のIDを1ずつ増やしていく
photonView.RPC(nameof(FireProjectile), RpcTarget.All, transform.position, angle);
}

}
}

// [PunRPC]属性をつけると、RPCでの実行が有効になる
[PunRPC]
private void FireProjectile(Vector3 origin, float angle, PhotonMessageInfo info)
{
int timestamp = info.SentServerTimestamp;
projectileManager.Fire(timestamp, photonView.OwnerActorNr, origin, angle, timestamp);

Debug.Log("Time" + timestamp);
Debug.Log("Origin" + origin);
Debug.Log("Info" + info);
Debug.Log("Owner" + photonView.OwnerActorNr);
}

private void OnTriggerEnter(Collider collision)
{
if (photonView.IsMine)
{
var projectile = collision.GetComponent<Projectile>();
if (projectile != null && projectile.OwnerId != PhotonNetwork.LocalPlayer.ActorNumber)
{
photonView.RPC(nameof(HitByProjectile), RpcTarget.All, projectile.Id, projectile.OwnerId);
}
}

if (collision.gameObject.tag == "Cube")// if (other.CompareTag(“Cube”))
{
Destroy(collision.gameObject);

Debug.Log(collision.gameObject.name);

if (photonView.IsMine)
{
GameObject canvas = GameObject.FindWithTag("CanvasUI");
InventoryTest inventorytest = canvas.GetComponentInChildren<InventoryTest>();

inventorytest.Add(item);
}
}
}

[PunRPC]
private void HitByProjectile(int projectileId, int ownerId)
{
projectileManager.Remove(projectileId, ownerId);

if (photonView.IsMine)
{
PhotonNetwork.LocalPlayer.OnTakeDamage();
}
else if (ownerId == PhotonNetwork.LocalPlayer.ActorNumber)
{
PhotonNetwork.LocalPlayer.OnDealDamage();
}
}

// プレイヤーのカスタムプロパティが更新された時に呼ばれるコールバック
public override void OnPlayerPropertiesUpdate(Player target, Hashtable changedProps)
{
if (target.ActorNumber != photonView.OwnerActorNr) { return; }

// スコアが更新されていたら、スコア表示も更新する
if (changedProps.TryGetScore(out int score))
{
nameLabel.text = $"{photonView.Owner.NickName}({score.ToString()})";
}

// 色相値が更新されていたら、スプライトの色を変化させる
if (changedProps.TryGetHue(out float hue))
{
spriteRenderer.material.color = Color.HSVToRGB(hue, 1f, 1f);
}
}
}

人気の記事

1

皆さん、ついに、エアラインでも、サブスクリプションが始まったのはご存じですか? まだ実験段階ですが、ANAが、定額全国住み放題サービスを提供する「ADDress」と組んで、国内線を4回まで定額利用可能 ...

2

無料でネットショップを開けるアプリとして多くの人に驚きを与えたBASE株式会社が、2019年10月25日東証マザーズに上場しました。2020年2月時点で90万店を超えるショップを抱えるまでに成長してい ...

3

2011年にサービスを開始してから圧倒的な成長率を誇るインテリア通販サイト 【FLYMEe/フライミー】を皆さんご存じでしょうか。 「自分のイメージするインテリア、本当に欲しいインテリアがどこにあるの ...

4

ついに、noteの月間アクティブユーザー数が4400万人(2020年3月時点)に到達しました。 そもそも、「note」とは、クリエイターが、文章やマンガ、写真、音声を投稿することができ、ユーザーはその ...

5

ボードゲームカフェが1日2回転で儲かるという記事をみつけたので興味を持ち、調べてみました。 まずは、需要がどれくらいあるのか、市場のようすからみていきましょう。 世界最大のボードゲーム市場はドイツで、 ...

-code, VR
-,

Copyright© BUSINESS HUNTER , 2023 All Rights Reserved Powered by AFFINGER5.