Search Unity

Bug Vector3.Reflect vs Vector2.Reflect

Discussion in 'Editor & General Support' started by Jicefrost, Oct 30, 2022.

  1. Jicefrost

    Jicefrost

    Joined:
    May 13, 2019
    Posts:
    40
    Hi all!
    I got 2 similar projects, first if 3D second 2D.
    First one bullet fly and do wall bounce for one time the code is -

    Code (CSharp):
    1. public class BulletBehaviour : MonoBehaviour
    2. {
    3.      [SerializeField]
    4.      private float bulletSpeed;
    5.      Vector3 newDirection;
    6.      Vector3 startPosition;
    7.  
    8.      private void Start()
    9.     {
    10.         startPosition = transform.position;
    11.     }
    12.  
    13.       private void Update()
    14.     {
    15.         bulletFly();
    16.     }
    17.  
    18.       private void bulletFly()
    19.     {
    20.         if (bulletHealth == 0) Destroy(gameObject);
    21.         Physics.Raycast(transform.position, transform.forward, out BulletHitPoint, 300);
    22.      }
    23.  
    24. private void OnTriggerEnter(Collider other)
    25.       {
    26.         if (other.tag == "Wall")
    27.         {
    28.             newDirection = Vector3.Reflect((BulletHitPoint.point - startPosition), BulletHitPoint.normal);
    29.             transform.rotation = Quaternion.LookRotation(newDirection);
    30.         }
    31.       }  
    32. }      
    33.        

    all work's great!
    But I cant do same thing with 2d sprites.

    2d game is same - bubbles "reflects" from the wall.

    code is similar -

    Code (CSharp):
    1. public class BubbleFlyScript : MonoBehaviour
    2. {
    3.     [SerializeField]
    4.     private float bubbleSpeed;
    5.     Vector2 startPosition;
    6.     RaycastHit2D hitpoint;
    7.     void Start()
    8.     {  
    9.         startPosition = transform.position;
    10.     }
    11.     void Update()
    12.     {
    13.         BubbleFly();
    14.     }
    15.  
    16.     private void BubbleFly()
    17.     {
    18.         hitpoint = Physics2D.Raycast(transform.position, transform.up);
    19.         transform.Translate(Vector2.up * bubbleSpeed * Time.deltaTime);  
    20.     }
    21.  
    22.  
    23.    private void OnTriggerEnter2D(Collider2D collision)
    24.     {
    25.         if (collision.tag == "Wall")
    26.         {
    27.             Vector3 newbubbleDirection = hitpoint.normal - startPosition;
    28.             Vector3 newDirection = Vector3.Reflect(newbubbleDirection, hitpoint.normal);
    29.             transform.rotation = Quaternion.LookRotation(newDirection);
    30.         }
    31.     }
    32. }
    walls sure have rigidbody2d and colliders2d. So 2d sprites after 'touch" the wall is "fly" anyway with some how Y rotated to 90 (why?) andbecause ofthat they become "flat" and did not seen on screen.

    Is this some how with different Physics2D and Physics raycast's ?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    Almost everything about 2D physics is different from 3D physics.

    Why? Because they're different systems, and one of them has a different number of "dees" than the other.

    Generally, if you're in 2D, attempt to do EVERYTHING in Vector2 math.

    The only exception is with scale, because doing it with Vector2 will leave the z element as zero. (See below)

    If you have no idea what is happening above, it is time to start debugging.

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

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    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.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    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

    When in doubt, print it out!(tm)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.

    The proper way to set scale:

    https://forum.unity.com/threads/onpointerenter-loose-image.1152686/#post-7396073

    NEVER set scale (or any part of scale) to zero or negative.

    NEVER use Vector2 because that makes the third term (Z) zero.

    ALWAYS use Vector3, and make sure that the .z is either 1.0f, or else your non-zero scale.

    Similarly never set scale to Vector3.zero, especially in a UI, because this will cause layout divide-by-zeros and damage all your hierarchy.
     
  3. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,842
    The issue is probably in your Quanternion.LookRotation use. It requires a 'forward' and 'up to orient the object, while you're only giving it a forward with it using the default 'up' of Vector3.Up.

    You probably want to give it a different forward direction so it orients itself towards the camera.
     
  4. Jicefrost

    Jicefrost

    Joined:
    May 13, 2019
    Posts:
    40
    Tanks you for advice. My mistake was that


    1. if (collision.tag == "Wall")
    2. {
    3. Vector3 newbubbleDirection = hitpoint.normal - startPosition;
    and right way was
    1. Vector3 newbubbleDirection = hitpoint.point- startPosition;
    now object is making right way but still invisible because of Y = 90.
    I change project make whole with with physics now. (it was on transform.translate)

    Now it is usual as every one do

    Code (CSharp):
    1.  private void OnCollisionEnter2D(Collision2D collisionToHit)
    2.     {
    3.         if (collisionToHit.gameObject.CompareTag("Wall"))
    4.         {
    5.         float collisionSpeed = lastVelocity.magnitude;
    6.         Vector2 reflect = Vector2.Reflect(lastVelocity.normalized, collisionToHit.contacts[0].normal);
    7.         rb.velocity = reflect * collisionSpeed;
    8.         }
    9. }
    topic may be closed
     
    Last edited: Nov 2, 2022