Reputation: 23
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);
}
}
Currently, I am making an arrow shooter.
I want to set arrow heading continuously while flying.
so I need to access "Aprefab" GameObject out of if
block.
but how?
Need some help
Upvotes: 0
Views: 70
Reputation: 168913
To expand upon my comment: I've
arrows
to keep track of all the arrows fired (that Shoot()
adds to)Update()
iterate over all the arrows and update themI don't have Unity at present, and this is dry-coded, so there might be some bugs.
Also, you'll want to take care of cleaning stuff up from the arrows
list at some point.
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);
}
}
Upvotes: 4