using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletScript : MonoBehaviour {
public float speed = 50f;
public Vector2 Player;
private Vector2 bulletDir = Vector2.zero;
void Start () {
// Get the current mouse position
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
// Calculate the bullet direction
bulletDir = (Player - mousePos).normalized;
}
void Update () {
if (bulletDir != Vector2.zero)
transform.Translate (bulletDir * speed * Time.deltaTime);
}
}
I’m trying to get the .position of my Player GameObject, then use some math to determine the angle at which my bullet will go to. I’m using .position as a vector2, but no matter how I declare the “Player” variable, it either isn’t compatible, or simply won’t work.
Right now, I have it set as a Vector2, at 0,0 in the editor, so all bullets fly in the direction of the origin.
Any ideas on how to do this? Player is a predefined GameObject currently in the editor, so when I figure out how to declare it properly I should be able to just drag it on there.
If “Player” is supposed to be a GameObject, then you can’t fit it into a Vector2.
If you want to drag your player object into that field, then you need to declare either one of those :
public GameObject player;
// or
public Transform player;
then you can access your player’s position by writting either **player.transform.position**
(for the gameObject) or **player.position**
(for the Transform).
The position is given as a Vector3, but it can be implicitely converted to Vector2. If you absolutely need to ignore the Z axis, then you can explicitly cast it with something like **(Vector2)player.position**
Hmm… I’ve tried to convert it to a transform and a gameobject, and while it compiles, it won’t let me assign the player gameobject to that variable for some reason.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletScript : MonoBehaviour {
public float speed = 50f;
public GameObject Player;
private Vector2 bulletDir = Vector2.zero;
void Start () {
// Get the current mouse position
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
// Calculate the bullet direction
bulletDir = ((Vector2)Player.transform.position - mousePos).normalized;
}
void Update () {
if (bulletDir != Vector2.zero)
transform.Translate (bulletDir * speed * Time.deltaTime);
}
}