- Home /
Question by
zekegomezgoldberg · Jun 09, 2020 at 08:56 PM ·
2d gameaddforce2d-physicsmouseposition2d platformer
Adding force to mouse position adds force relative to screen center
(Disclaimer: I'm very new to coding and unity, my code is basically patchwork from different tutorials)
This is my code for a grenade projectile that is meant to shoot towards the mouse position once created by the grenade launcher.
My problem is that the mouse position seems relative to the center of the screen. Ex: I have the player positioned at the bottom center of the screen. I click to the top left of the character, which happens to be directly left of the screen center. The character then shoots the grenade directly left, instead of to the top left. I would appreciate any and all help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class Projectile : MonoBehaviour
{
public float speed;
public Rigidbody2D rb;
public float fieldOfImpact;
public float force;
public LayerMask LayerToHit;
private void Start()
{
Vector3 newPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
GetComponent<Rigidbody2D>().AddForce(newPosition * speed);
}
Comment