Hello all,
I am a complete begginier to Unity and c#. However I have recently been trying to create a 2D game by following tutorials and I have run into an issue with some script in C# and was hoping that someonw could help. My aim is to make it so that the player can move both left and right on a surface and they will shoot in the corresponding direction rather than currently always right. I have had a gok and this, trying to use a few different ideas but just cant crack it. In addition, I was also hoping to add the ability too shoot upwards when a certain key is pressed on the keyboard. Many thanks, Josh. Here is the Script:
Bullet:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bullet : MonoBehaviour
{
public float speed = 20f;
public int damage = 40;
public Rigidbody2D rb;
public GameObject impactEffect;
// Use this for initialization
void Start()
{
rb.velocity = transform.right * speed;
}
void OnTriggerEnter2D(Collider2D hitInfo)
{
Health enemy = hitInfo.GetComponent();
if (enemy != null)
{
enemy.TakeDamage(damage);
if (damage == 100)
{
Destroy(gameObject);
}
}
Instantiate(impactEffect, transform.position, transform.rotation);
//Destroy(gameObject);
}
}
Weapon:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown(“Fire1”))
{
Shoot();
}
}
void Shoot()
{
//shooting logic
Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
}
}
Player Controller:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed;
Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent();
}
// Update is called once per frame
void Update()
{
}
void FixedUpdate()
{
float move = Input.GetAxis(“Horizontal”);
rb.velocity = new Vector2(speed * move, rb.velocity.y);
}
}