Hello everyone!
I’ll make the premise that i’m very new to the Unity world and i’ve been searching for a working solution the past day.
So, i am trying to implement the logic behind firing projectiles towards my mouse cursor (mobile touch later on since i’m targeting android) from a fixed origin (the character can’t move, only fire). I attached a Rigidbody2D to the projectiles and the script that generate those set the target point after instantiating, after that the rest is left in the hands of the “MoveProjectile” script i have put on the projectile prefab.
Here is the script code (it’s short so i’m posting it fully):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProjectileMove : MonoBehaviour
{
public Vector3 target;
public float speed = 6.0f;
private Vector2 movement;
private Rigidbody2D rigidbody;
void Start()
{
rigidbody = GetComponent<Rigidbody2D>();
var direction = (target - transform.position);
direction = direction.normalized;
movement = direction * speed;
}
void FixedUpdate()
{
//GetComponent<Rigidbody2D>().AddForce(projectileInst.transform.forward * 1000);
rigidbody.MovePosition(rigidbody.position + movement * Time.fixedDeltaTime);
}
}
Both methods (using AddForce and MovePosition) successfully move the projectiles towards the mouse click location, however the linear velocity of each bullet depends from the distance between spawn origin and mouse click location, as you can see from the following images:
- Clicking on the extreme right of the game screen:
- Clicking right on top of the spawn origin:
Debug logs show that the normalized vector shrinks the closer i get to the origin while i was expecting it to preserve the unitary magnitude…
It feels like i’m missing something but i can’t really grasp it…