Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved Getting Mouse Position after Mouse Up

Discussion in 'Scripting' started by rubenoriginal, May 9, 2022.

  1. rubenoriginal

    rubenoriginal

    Joined:
    Apr 23, 2018
    Posts:
    5
    Hey,

    I'm currently attempting to fix an issue with my game.

    The player drags with the mouse and is able to shoot a ball (similar to like Angry Birds)

    The character in the scene plays an animation, and after the animation ends the ball launches (the reality is, the ball is hidden and appears 0.25 seconds later at an approximate position of the hand of the character)

    The issue is that if the player moves the mouse before those 0.25 seconds, the trajectory completely changes and the ball ends up being thrown in the last detected location, not the intented initial one.

    Someone mentioned to store the mouse position on mouse up instead of grabbing it from throwBall(). But my attempts at changing the code to do so have all failed.

    Any help is appreciated. I'll leave code below, it's a code from a tutorial that i've slightly modified to fit in my project.

    Issue Demostration:


    And the code:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class BallTest : MonoBehaviour
    7. {
    8.     public float force = 100f;
    9.  
    10.     public GameObject ballPrediction;
    11.     public int maxTrajectoryIteration = 30;
    12.     public MeshRenderer Pelota;
    13.     public Collider2D PelotaCol;
    14.     public float time;
    15.  
    16.     private Vector3 defaultBallPosition;
    17.     private Vector3 startPosition;
    18.     private Rigidbody2D physics;
    19.     private Scene sceneMain;
    20.     private PhysicsScene2D sceneMainPhysics;
    21.     private Scene scenePrediction;
    22.     private PhysicsScene2D scenePredictionPhysics;
    23.  
    24.     private float ballScorePosition;
    25.  
    26.     public AudioClip[] sounds;
    27.     public AudioSource MaleBallThrow;
    28.  
    29.  
    30.     void Awake()
    31.     {
    32.         physics = GetComponent<Rigidbody2D>();
    33.     }
    34.  
    35.     void EnableBall()
    36.     {
    37.         PelotaCol.enabled = true;
    38.         Pelota.enabled = true;
    39.         physics.isKinematic = false;
    40.         throwBall(physics);
    41.     }
    42.  
    43.     void Start()
    44.     {
    45.         Physics2D.simulationMode = SimulationMode2D.Script;
    46.  
    47.         physics.isKinematic = true;
    48.         defaultBallPosition = transform.position;
    49.  
    50.         createSceneMain();
    51.         createScenePrediction();
    52.  
    53.         Cursor.visible = true;
    54.     }
    55.  
    56.     private void createSceneMain()
    57.     {
    58.         sceneMain = SceneManager.CreateScene("MainScene");
    59.         sceneMainPhysics = sceneMain.GetPhysicsScene2D();
    60.     }
    61.  
    62.     private void createScenePrediction()
    63.     {
    64.         CreateSceneParameters sceneParameters = new CreateSceneParameters(LocalPhysicsMode.Physics2D);
    65.         scenePrediction = SceneManager.CreateScene("PredictionScene", sceneParameters);
    66.         scenePredictionPhysics = scenePrediction.GetPhysicsScene2D();
    67.     }
    68.  
    69.     bool ballshot = false;
    70.     bool line = false;
    71.  
    72.     void Update()
    73.     {
    74.         if (Input.GetMouseButtonDown(0))
    75.         {
    76.             {
    77.                 startPosition = getMousePosition();
    78.             }
    79.         }
    80.  
    81.         if (Input.GetMouseButton(0))
    82.         {
    83.             if (!line)
    84.             {
    85.                 GameObject newBallPrediction = spawnBallPrediction();
    86.                 throwBall(newBallPrediction.GetComponent<Rigidbody2D>());
    87.                 createTrajectory(newBallPrediction);
    88.                 Destroy(newBallPrediction);
    89.             }
    90.         }
    91.  
    92.         if (Input.GetMouseButtonUp(0))
    93.         {
    94.             if (!ballshot)
    95.             {
    96.                 GetComponent<LineRenderer>().positionCount = 0;
    97.                 line = true;
    98.                 Invoke("EnableBall", time);
    99.                 ballshot = true;
    100.                 MaleBallThrow.clip = sounds[Random.Range(0, sounds.Length)];
    101.                 MaleBallThrow.PlayOneShot(MaleBallThrow.clip);
    102.             }
    103.         }
    104.  
    105.     }
    106.  
    107.     private void createTrajectory(GameObject newBallPrediction)
    108.     {
    109.         LineRenderer ballLine = GetComponent<LineRenderer>();
    110.         ballLine.positionCount = maxTrajectoryIteration;
    111.  
    112.         for (int i = 0; i < maxTrajectoryIteration; i++)
    113.         {
    114.             scenePredictionPhysics.Simulate(Time.fixedDeltaTime);
    115.             ballLine.SetPosition(i, new Vector3(newBallPrediction.transform.position.x, newBallPrediction.transform.position.y, 0));
    116.         }
    117.     }
    118.  
    119.     private void throwBall(Rigidbody2D physics)
    120.     {
    121.         physics.AddForce(getThrowPower(startPosition, getMousePosition()), ForceMode2D.Force);
    122.     }
    123.  
    124.     private GameObject spawnBallPrediction()
    125.     {
    126.         GameObject newBallPrediction = GameObject.Instantiate(ballPrediction);
    127.         SceneManager.MoveGameObjectToScene(newBallPrediction, scenePrediction);
    128.         newBallPrediction.transform.position = transform.position;
    129.  
    130.         return newBallPrediction;
    131.     }
    132.  
    133.  
    134.     private Vector3 getThrowPower(Vector3 startPosition, Vector3 endPosition)
    135.     {
    136.         return (startPosition - endPosition) * force;
    137.     }
    138.  
    139.     void FixedUpdate()
    140.     {
    141.         if (!sceneMainPhysics.IsValid()) return;
    142.  
    143.         sceneMainPhysics.Simulate(Time.fixedDeltaTime);
    144.     }
    145.  
    146.     private Vector3 getMousePosition()
    147.     {
    148.         return Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z - Camera.main.transform.position.z));
    149.     }
    150.  
    151. }
    152.  
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    That's probably the correct answer, and it should be trivial to implement.

    If you are running into difficulty, here is how to isolate what you are doing wrong:

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    You must find a way to get the information you need in order to reason about what the problem is.
     
  3. rubenoriginal

    rubenoriginal

    Joined:
    Apr 23, 2018
    Posts:
    5
    The issue is now fixed:

    This is the new code (although worse, but it works as of now)

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class BallTest : MonoBehaviour
    7. {
    8.     public float force = 100f;
    9.  
    10.     public GameObject ballPrediction;
    11.     public int maxTrajectoryIteration = 30;
    12.     public MeshRenderer BallMesh;
    13.     public Collider2D BallCollider;
    14.     public float time;
    15.  
    16.     private Vector3 defaultBallPosition;
    17.     private Vector3 startPosition;
    18.     private Vector3 endPosition;
    19.     private Vector3 mouseUp;
    20.     private Vector3 dragPosition;
    21.     private Rigidbody2D Basketball;
    22.     private Scene sceneMain;
    23.     private PhysicsScene2D sceneMainPhysics;
    24.     private Scene scenePrediction;
    25.     private PhysicsScene2D scenePredictionPhysics;
    26.  
    27.     private float ballScorePosition;
    28.  
    29.     public AudioClip[] sounds;
    30.     public AudioSource MaleBallThrow;
    31.  
    32.     private Vector3 mouseUpPosition;
    33.  
    34.     void Awake()
    35.     {
    36.         Basketball = GetComponent<Rigidbody2D>();
    37.     }
    38.  
    39.     void EnableBall()
    40.     {
    41.         endPosition = mouseUpPosition;
    42.         Vector3 dragPosition = getMousePosition();
    43.         Vector3 power = startPosition - endPosition;
    44.         BallMesh.enabled = true;
    45.         BallCollider.enabled = true;
    46.         Basketball.isKinematic = false;
    47.         Basketball.AddForce(power * force, ForceMode2D.Force);
    48.     }
    49.  
    50.     void Start()
    51.     {
    52.         Physics2D.simulationMode = SimulationMode2D.Script;
    53.  
    54.         Basketball.isKinematic = true;
    55.         defaultBallPosition = transform.position;
    56.  
    57.         createSceneMain();
    58.         createScenePrediction();
    59.  
    60.         Cursor.visible = true;
    61.     }
    62.  
    63.     private void createSceneMain()
    64.     {
    65.         sceneMain = SceneManager.CreateScene("MainScene");
    66.         sceneMainPhysics = sceneMain.GetPhysicsScene2D();
    67.     }
    68.  
    69.     private void createScenePrediction()
    70.     {
    71.         CreateSceneParameters sceneParameters = new CreateSceneParameters(LocalPhysicsMode.Physics2D);
    72.         scenePrediction = SceneManager.CreateScene("PredictionScene", sceneParameters);
    73.         scenePredictionPhysics = scenePrediction.GetPhysicsScene2D();
    74.     }
    75.  
    76.     bool ballshot = false;
    77.     bool line = false;
    78.  
    79.     void Update()
    80.     {
    81.         if (Input.GetMouseButtonDown(0))
    82.         {
    83.             {
    84.                 startPosition = getMousePosition();
    85.             }
    86.         }
    87.  
    88.         if (Input.GetMouseButton(0))
    89.         {
    90.             if (!line)
    91.             {
    92.                 Vector3 dragPosition = getMousePosition();
    93.                 Vector3 power = startPosition - dragPosition;
    94.  
    95.                 GameObject newBallPrediction = GameObject.Instantiate(ballPrediction);
    96.                 SceneManager.MoveGameObjectToScene(newBallPrediction, scenePrediction);
    97.                 newBallPrediction.transform.position = transform.position;
    98.                 newBallPrediction.GetComponent<Rigidbody2D>().AddForce(power * force, ForceMode2D.Force);
    99.                 createTrajectory(newBallPrediction);
    100.                 Destroy(newBallPrediction);
    101.             }
    102.         }
    103.  
    104.         if (Input.GetMouseButtonUp(0))
    105.             if (!ballshot)
    106.             {
    107.  
    108.                 mouseUp = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z - Camera.main.transform.position.z));
    109.                 mouseUpPosition = mouseUp;
    110.                 endPosition = mouseUpPosition;
    111.  
    112.                 Vector3 power = startPosition - endPosition;
    113.  
    114.  
    115.                 GetComponent<LineRenderer>().positionCount = 0;
    116.                 line = true;
    117.                 Invoke("EnableBall", time);
    118.                 ballshot = true;
    119.                 MaleBallThrow.clip = sounds[Random.Range(0, sounds.Length)];
    120.                 MaleBallThrow.PlayOneShot(MaleBallThrow.clip);
    121.             }
    122.  
    123.  
    124.     }
    125.  
    126.     private Vector3 getThrowPower(Vector3 startPosition, Vector3 endPosition)
    127.     {
    128.         return (startPosition - endPosition) * force;
    129.     }
    130.  
    131.     private void createTrajectory(GameObject newBallPrediction)
    132.     {
    133.         LineRenderer ballLine = GetComponent<LineRenderer>();
    134.         ballLine.positionCount = maxTrajectoryIteration;
    135.  
    136.         for (int i = 0; i < maxTrajectoryIteration; i++)
    137.         {
    138.             scenePredictionPhysics.Simulate(Time.fixedDeltaTime);
    139.             ballLine.SetPosition(i, new Vector3(newBallPrediction.transform.position.x, newBallPrediction.transform.position.y, 0));
    140.         }
    141.     }
    142.  
    143.  
    144.     void FixedUpdate()
    145.     {
    146.         if (!sceneMainPhysics.IsValid()) return;
    147.  
    148.         sceneMainPhysics.Simulate(Time.fixedDeltaTime);
    149.     }
    150.  
    151.     private Vector3 getMousePosition()
    152.     {
    153.         return Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z - Camera.main.transform.position.z));
    154.     }
    155.  
    156.     private Vector3 getMouseUpPosition()
    157.     {
    158.         return Camera.main.ScreenToWorldPoint(Input.mousePosition);
    159.     }
    160.  
    161. }
    162.