I am making a top down 2d “game” and have been using this code from the brakeys tutorial
and a basic movement script
with this shooting script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooting : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
public AudioSource audio;
public AudioClip impact;
public float bulletForce = 20f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
Shoot();
}
}
void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
Physics2D.IgnoreCollision(bullet.GetComponent<Collider2D>(), GetComponent<Collider2D>());
audio.PlayOneShot(impact, 0.7F);
}
void ShootDown()
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(firePoint.right * bulletForce, ForceMode2D.Impulse);
Physics2D.IgnoreCollision(bullet.GetComponent<Collider2D>(), GetComponent<Collider2D>());
audio.PlayOneShot(impact, 0.7F);
}
}
and with this movement script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public Rigidbody2D rb;
Vector2 movement;
void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
}
void FixedUpdate()
{
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
}
}
the problem is with this that it is only shooting upwards and i need it to be shooting based on player movement direction and i can’t think of a solution.
i have tried using methods from this thread Rotating FirePoint
but it says “rb and firePointL doesent exist in this context” when i tried implementing it into my code.
This is the backeys tutorial i used:
https://www.youtube.com/watch?v=LNLVOjbrQj4
(This is my first ever unity project and i dont really understand everything in csharp yet.) Is
Is there a way to do this thats simple enough?
(maybe based on the x and y movement of the player)
8937930–1225827–Shooting.cs (1.42 KB)