Hey,
I’m building a 2D project where I will have two spaceships that battle to get the most of their own color on the ground (bombit, splatoon, etc. inspired).
I’m stuck at creating a shot mechanic where the player can holds space and the shot Instantiates infront of the player on the “shotPosition” (it charges, gets more powerful while doing this) while the player is moving, until you release the space-button and the shot gets fired away forward.
I have been stuck on this for hours.
Thanks in advance
(On the picture you can see the spaceShip and shotPos).
Here is my code for the movementScript:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player1_Controller : MonoBehaviour {
//Int and Floats
public int turnSpeed;
public float maxSpeed;
public float defaultPower;
public float charge;
public float maxPower;
public float reloadTimer = 1f;
private bool isUp = false;
private bool canShoot = true;
// Gameobjects and Transforms
public Transform shotPos;
// Rigidbody
Rigidbody2D rb2d;
public Rigidbody2D shotPrefab;
// Use this for initialization
void Start ()
{
rb2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
float yAxis = Input.GetAxis("W_S") * maxSpeed;
float xAxis = Input.GetAxis("A_D");
MovementForward(yAxis);
Turning(transform, xAxis * -turnSpeed);
Shooting();
}
private void MovementForward(float amount)
{
Vector2 force = transform.up * amount;
rb2d.AddForce(force * Time.deltaTime);
}
private void Turning(Transform t, float amount)
{
t.Rotate(0, 0, amount * Time.deltaTime);
}
private void Shooting()
{
if (Input.GetKey(KeyCode.Space) && charge < maxPower)
{
charge += Time.deltaTime * 30;
}
if (Input.GetKeyUp(KeyCode.Space) && canShoot == true)
{
Rigidbody2D shot;
shot = Instantiate(shotPrefab, shotPos.position, shotPos.rotation) as Rigidbody2D;
shot.AddForce(shotPos.up * charge);
charge = defaultPower;
canShoot = false;
}
else if (canShoot == false)
{
reloadTimer -= Time.deltaTime;
if (reloadTimer <= 0)
{
reloadTimer = 1f;
canShoot = true;
}
}
}
}