Question by
FlyingTurtleMan · Oct 28, 2017 at 08:29 AM ·
shootingnot working2d platformer
How do you make a projectrile go the direction the player is facing?
I am very new to Unity and I am making my first game. I want it so that when I click 'k' a fireball is shot in the direction the player is facing. What happens is that the fire will always move right. The Debug.DrawLine works properly. Can someone please help me out.
Script that moves the fire using UnityEngine; using UnityStandardAssets._2D;
public class MoveTrail : MonoBehaviour {
public int moveSpeed = 150;
public GameObject player;
// Update is called once per frame
void Update () {
if (player.GetComponent<PlatformerCharacter2D>().m_FacingRight == true)
{
transform.Translate(Vector3.right * Time.deltaTime * moveSpeed);
Destroy(gameObject, 1);
}
else
{
transform.Translate(Vector3.left * Time.deltaTime * moveSpeed);
Destroy(gameObject, 1);
}
}
}
Shooting script using UnityEngine;
public class shoot : MonoBehaviour {
public float Damage = 10;
public LayerMask whatToHit;
public Transform BulletTrailPrefab;
Transform firePoint;
Transform hitPoint;
// Use this for initialization
void Awake()
{
firePoint = transform.Find("FirePoint");
if (firePoint == null)
{
Debug.LogError("Boi there be no firepoint");
}
hitPoint = transform.Find("HitPoint");
if (hitPoint == null)
{
Debug.LogError("Boi there be no hitpoint");
}
}
// Update is called once per frame
void Update ()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
Vector2 firePointPosition = new Vector2(firePoint.position.x, firePoint.position.y);
Vector2 hitPointPosition = new Vector2(hitPoint.position.x, hitPoint.position.y);
RaycastHit2D hit = Physics2D.Raycast(firePointPosition, hitPointPosition - firePointPosition, 100, whatToHit);
Effect();
Debug.DrawLine(firePointPosition, (hitPointPosition - firePointPosition) * 100, Color.magenta);
if (hit.collider != null)
{
Debug.DrawLine(firePointPosition, hit.point, Color.red);
}
}
void Effect()
{
Instantiate(BulletTrailPrefab, firePoint.position, firePoint.rotation);
}
}
Comment
Best Answer
Answer by ProfessorDodo · Oct 28, 2017 at 01:51 PM
You never set a rotation for firePoint. Try this:
Instantiate(BulletTrailPrefab, firePoint.position,
Quaternion.LookRotation(hitPointPosition - firePointPosition));
Thankyou for answering. With your suggestion and a bit of tweaking, I was able to get it mostly working. Now the fireballs are spawning with a rotation on the y axis of 90 degrees, and since this is a 2D game, you can not see the fireballs. How can I fix this?