using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControl : MonoBehaviour {
public GameObject player;
public GameObject arrow;
private Vector3 a;
private float angle;
private Rigidbody2D rb2D;
void Start()
{
}
void Update () {
if (Input.GetMouseButtonDown(0))
{
a = Input.mousePosition;
Vector2 difference = a - player.transform.position;
GameObject Aprefab = Instantiate(arrow) as GameObject;
rb2D = Aprefab.GetComponent<Rigidbody2D>();
rb2D.AddForce(difference * 0.02f, ForceMode2D.Impulse);
}
angle = Mathf.Atan2(rb2D.velocity.y, rb2D.velocity.x);
Aprefab.transform.localEulerAngles = new Vector3(0, 0, (angle * 180) / Mathf.PI);
}
}
目前,我正在制作射箭游戏。
我想在飞行时连续设置箭头方向。
因此我需要从if
块中访问“ Aprefab” GameObject。
但是如何?
需要帮助
答案 0 :(得分:4)
根据我的评论扩展:我已经
arrows
,以跟踪发射的所有箭头(Shoot()
添加到其中)Update()
遍历所有箭头并进行更新我目前没有Unity,并且此代码是干式编码的,因此可能存在一些错误。
另外,您有时会需要清理arrows
列表中的内容。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControl : MonoBehaviour {
public GameObject player;
private List<GameObject> arrows = new List<GameObject>();
void Start()
{
}
void Update () {
if (Input.GetMouseButtonDown(0))
{
Shoot();
}
foreach(var arrow in arrows) {
var rb2D = Aprefab.GetComponent<Rigidbody2D>();
var angle = Mathf.Atan2(rb2D.velocity.y, rb2D.velocity.x);
arrow.transform.localEulerAngles = new Vector3(0, 0, (angle * 180) / Mathf.PI);
}
}
private void Shoot() {
var a = Input.mousePosition;
var difference = a - player.transform.position;
var Aprefab = Instantiate(arrow) as GameObject;
var rb2D = Aprefab.GetComponent<Rigidbody2D>();
rb2D.AddForce(difference * 0.02f, ForceMode2D.Impulse);
arrows.Add(Aprefab);
}
}