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;
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;
GameObject newProjectile = (GameObject) Instantiate(projectilePrefab, myPosition, Quaternion.identity);
projectileRB.velocity = direction * speed;
@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).
newProjectile.GetComponent<Rigidbody2D>().velocity = direction * speed;