- Home /
How to make projectile move towards mouse position
I cannot for the life of me get this to work. Whenever I press play and left click, a projectile just gets Instantiated right in the middle of my player with no movement... can anyone help?
public class PlayerShooting : MonoBehaviour
{
public GameObject projectilePrefab;
Rigidbody2D projectileRB;
Vector2 playerLook;
Vector2 direction;
Vector2 myPosition;
public float speed = 5f;
private void Start()
{
projectileRB = projectilePrefab.GetComponent<Rigidbody2D>();
}
private void Update()
{
playerLook = Camera.main.ScreenToWorldPoint(Input.mousePosition);
myPosition = new Vector2(transform.position.x, transform.position.y);
direction = playerLook - myPosition;
direction.Normalize();
if(Input.GetMouseButtonDown(0))
{
GameObject newProjectile = (GameObject) Instantiate(projectilePrefab, myPosition, Quaternion.identity);
projectileRB.velocity = direction * speed;
}
}
}
Answer by Priyanka-Rajwanshi · Apr 20, 2020 at 11:13 AM
@Noaaaa1 There are two issues in your code. First, Camera.main.ScreenToWorldPoint requires a Vector3 and Input.mousePosition gives the Vector3 with z-position = 0 which does not coincide with the z-position of your object. So use these lines to find playerLook:
Vector3 myScreenPos = Camera.main.WorldToScreenPoint(transform.position);
playerLook = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, myScreenPos.z));
For understanding the code snippet, you can use this link: http://codesaying.com/understanding-screen-point-world-point-and-viewport-point-in-unity3d/
Secondly, you are applying velocity to the prefab(which is not present in the scene), although you have to apply velocity to the object that has been instantiated ie. to newProjectile(which is present in the scene). So write:
newProjectile.GetComponent<Rigidbody2D>().velocity = direction * speed;
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Problem with bullet moving in straight line 3 Answers
Drawing a straight line between two points with 2D UI 1 Answer
C# Projectile Ricochet After Collision2d 1 Answer
Simple jump code 2D - c# 1 Answer