Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

2d TopDown Shooter (Towards Mouse Pos & Without Stopping)

Discussion in '2D' started by WildHunt777, Jul 1, 2020.

  1. WildHunt777

    WildHunt777

    Joined:
    Dec 27, 2019
    Posts:
    2
    Hello, Unity community.
    I've got a problem with shooting at the mouse position, but then I want the bullet not to stop, but to keep going.

    transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);


    Thanks for any response as well.
     
  2. WildHunt777

    WildHunt777

    Joined:
    Dec 27, 2019
    Posts:
    2
    The whole code here:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Projectile : MonoBehaviour
    6. {
    7.     public float speed;
    8.     public int damage;
    9.     public GameObject shootEffect;
    10.    
    11.     Vector2 target;
    12.  
    13.  
    14.     void Start()
    15.     {
    16.         target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    17.     }
    18.  
    19.     void Update()
    20.     {
    21.             transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
    22.  
    23.             if(Vector2.Distance(transform.position, target) < 0.2f)
    24.             {
    25.                 Instantiate(shootEffect, transform.position, Quaternion.identity);
    26.                 Destroy(gameObject);
    27.             }
    28.     }
    29.  
    30.     void OnTriggerEnter2D(Collider2D other)
    31.     {
    32.         if (other.CompareTag("Enemy"))
    33.         {
    34.             Instantiate(shootEffect, transform.position, Quaternion.identity);
    35.         }
    36.         if (other.CompareTag("EnemyProjectile"))
    37.         {
    38.             Instantiate(shootEffect, transform.position, Quaternion.identity);
    39.         }
    40.     }
    41.  
    42. }
     
  3. Phan-Phantz

    Phan-Phantz

    Joined:
    Nov 11, 2015
    Posts:
    15
    I recommend you use Rigidbody2D.velocity to move the bullet instead. You can set bullet's velocity to with the direction multiply by speed, something like this:

    rigidbody.velocity = (Vector2)(target - transform.position) * speed;
     
  4. GrizzlyPunchGames

    GrizzlyPunchGames

    Joined:
    May 21, 2020
    Posts:
    11
    hi i have created tutorial about 2d shooting,
    If youy want you can check that: