Home > Enterprise >  How can I make a 2D gun shoot towards the Direction of the mouse rather than the Position of the mou
How can I make a 2D gun shoot towards the Direction of the mouse rather than the Position of the mou

Time:06-19

Currently, my gun is able to instantiate new bullets that work fine (they have velocity and shoot towards the mouse's position). However, if the mouse is close to the player, I noticed the velocity is drastically lessened because it is targeting the mouse's position instead of the general direction.

Is there a way to get the angle from the player to the mouse, as well as apply velocity to the bullet, without it going exactly to the mouse's position?

public GameObject bullet;
public GameObject player;


// All the following is within an update function

//Gets the mouse position, and assigns direction from gun to mouse
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = mousePosition - transform.position;
float angle = Vector2.SignedAngle(Vector2.right, direction);

Vector2 PlayerDimensions = player.transform.lossyScale;
Vector2 PlayerLocation = player.transform.position;


//If the Gun weapon type is selected
if (weaponType == 2)
{
   // Is used to flip the player sprite based on if the gun is facing left or right
   if (PlayerLocation.x > mousePosition.x)
   {
      PlayerDimensions.x = -1;
      player.transform.localScale = new Vector2(PlayerDimensions.x, PlayerDimensions.y);
   }
   else if (PlayerLocation.x < mousePosition.x)
   {
      PlayerDimensions.x = 1;
      player.transform.localScale = new Vector2(PlayerDimensions.x, PlayerDimensions.y);
   }
   // Aims the gun based on if player is facing left or right
   if (player.transform.lossyScale.x > 0)
   {
      transform.eulerAngles = new Vector3(0, 0, angle);
   }
   else if (player.transform.lossyScale.x < 0)
   {
      transform.eulerAngles = new Vector3(0, 0, 180   angle);
   }
}

if (Input.GetMouseButtonDown(0) && weaponType == 2)
{
   Debug.Log("Shoot");

   Vector3 myPos = new Vector3(transform.position.x, transform.position.y);
   GameObject Bullet = Instantiate(bullet, myPos, Quaternion.identity);
   Physics2D.IgnoreCollision(Bullet.GetComponent<BoxCollider2D>(), player.GetComponent<BoxCollider2D>(), GameObject.Find("blue_bullet_medium(Clone)"));

   Bullet.GetComponent<Rigidbody2D>().velocity = new Vector2(direction.x, direction.y);
}

CodePudding user response:

You can use normalized vector and speed instead of just direction to get constant bullet speed. In code it will be like this:

Vector2 direction = mousePosition - transform.position;
direction.Normalize();
Vector2 bulletVelocity = direction * _speed; // assume _speed can be tuned

The normalized vector will always have length 1, so the speed will not depend on the distance from the player to the cursor position

  • Related