- Home /
 
Move projectile in a specific direction
I'm trying to fire a projectile in a direction of a touch on screen. Here is the code i've come up with :
 if (Input.touchCount > 0)
         {
             Touch t = Input.touches[0];
             if(t.phase == TouchPhase.Began)
             {
                 Vector2 position = new Vector2(0, -4);
                 Vector2 target = Camera.main.ScreenToWorldPoint(t.position);
 
                 GameObject projectile = Instantiate(_projectilePrefab, position, Quaternion.identity);
                 projectile.GetComponent<Cannonball>().Position = position;
                 projectile.GetComponent<Cannonball>().Target = target;
                 projectile.GetComponent<Cannonball>().Speed = 4f;
                 _projectiles.Add(projectile);        
             }
         }
 
               And inside the Cannonball class :
 public class Cannonball : MonoBehaviour
 {
     private Vector3 _direction;
     public Vector2 Target { get; set; }
     public Vector2 Position { get; set; }
     public float Speed { get; set; }
     
     // Use this for initialization
     void Start()
     {
         _direction = (Position - Target).normalized;
     }
     // Update is called once per frame
     void Update()
     {
         Move();
     }
     private void Move()
     {
         Position = transform.position - (_direction * (Speed * Time.deltaTime));
         transform.position = Position; 
     }
 }
 
               It seems to work but somehow the projectile stop at the beginning of the motion. Here is a link to a screencap i've taken : Screen capture
So you want it to fire from the cannon towards the position of where the player touched? If so then why dont you use a rididbody2d and addforce in the direction of the position touched.
Your answer
 
             Follow this Question
Related Questions
help with making enemy projectile fly at player at one speed 0 Answers
the projectile reflects 1 time only when it hits something, pls help! 1 Answer
sidescroller: flipping sides of player based on direction (C#) 1 Answer
Finding the direction an object is moving and giving it a destination 1 Answer
UFPS Projectile Spawn Point (SOLVED) 2 Answers