- Home /
Aiming a shot in Unity 2d?
Hello, I'm working on a 2d platformer project involving a grappling hook. I'm currently trying to script a basic projectile fired by the player. I followed a tutorial for doing so in a 2d shooter, using a shot prefab (with it's own "movement" and "shot" scripts) fired by a "WeaponScript" attached to the player character.
The problem is that this only fires the shot straight forward. I'd like for the shot to be fired in whatever direction the player character is facing, or whatever direction the player is holding on the game pad/keyboard.
Here is the weapon script attached to the player:
using UnityEngine;
public class WeaponScript : MonoBehaviour
{
public Transform shotPrefab;
public float shootingRate = 0.25f;
private float shootCooldown;
void Start()
{
shootCooldown = 0f;
}
void Update()
{
if (shootCooldown > 0)
{
shootCooldown -= Time.deltaTime;
}
}
public void Attack(bool isEnemy)
{
if (CanAttack)
{
shootCooldown = shootingRate;
// Create a new shot
var shotTransform = Instantiate(shotPrefab) as Transform;
// Assign position
shotTransform.position = transform.position;
// The is enemy property
ShotScript shot = shotTransform.gameObject.GetComponent<ShotScript>();
if (shot != null)
{
shot.isEnemyShot = isEnemy;
}
// Make the weapon shot always towards it
MoveScript move = shotTransform.gameObject.GetComponent<MoveScript>();
if (move != null)
{
move.direction = this.transform.right; // towards in 2D space is the right of the sprite
}
}
}
public bool CanAttack
{
get
{
return shootCooldown <= 0f;
}
}
}
I can tell the problem probably lies in the "move.direction = this.transform.right;" I have a function in my player character movement script that flips the sprite when moving in another direction, but I don't know how to flip this along with it.
Your answer
Follow this Question
Related Questions
animation 2d platformer 2 Answers
jittery jumping 2D character 0 Answers
2D shooter plataform aim,tutorial please? 1 Answer
switching between different screen boxes 2 Answers
2D Buttons 1 Answer