Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Even ChatGPT is unable to help me with that code. I tried to do my first game PONG.

Discussion in 'Scripting' started by Fox-Random, Aug 20, 2023.

  1. Fox-Random

    Fox-Random

    Joined:
    Dec 26, 2022
    Posts:
    4
    Well. Maybe I will let You know what I am trying to achive. There is a ball and on the beginning I want to generate random direction for it after ball (with rigidbody) hits a wall (with rigidbody) schoud bounce and have same speed as before but reflected direction. On the beggining I did it in plane closed with 4 walls so it can happend forever just for test reasons.

    MY results : balls moves with desired speed and direction but after touching the wall its stops kinda.

    Sorry this code is completly DIY and I wanted to do a bit of my invention just to get some practice. Make mistake and learn as they say.


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class BallMovement : MonoBehaviour
    6. {
    7.     private Rigidbody ballRb;
    8.     public float speed = 1f;
    9.     public Vector3 initialDirection, actualDirection, reflectedDirection;
    10.  
    11.     // Start is called before the first frame update
    12.     void Start()
    13.     {
    14.         ballRb = GetComponent<Rigidbody>();
    15.         initialDirection = genInitDirection();
    16.         ballRb.velocity  = initialDirection * speed;
    17.     }
    18.  
    19.     // Update is called once per frame
    20.     void Update()
    21.     {
    22.        // ballRb.transform.position += ballRb.velocity * Time.deltaTime;
    23.     }
    24.  
    25.     public Vector3 genInitDirection()
    26.     {
    27.         int x = (Random.Range(0, 2) * 2) -1 ;
    28.         float z = Random.Range(-1f, 1f);
    29.         Vector3 normInitDirect = new Vector3(x, 0, z).normalized;
    30.         return normInitDirect;
    31.     }
    32.  
    33.     private void OnCollisionEnter(Collision collision)
    34.     {
    35.         actualDirection = collision.contacts[0].normal;
    36.         reflectedDirection = Vector3.Reflect(reflectedDirection, actualDirection);
    37.         ballRb.velocity = reflectedDirection * speed;
    38.     }
    39.  
    40.      
    41. }
    42.  
     
  2. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    I would do as most of us do, when we're stuck on something that someone else has already figured out, google it. I found a supposed quick tutorial:

    Then look at what they do, and figure out why your code is different. Then deep dive research things or methods you haven't come across yet, to get a better understanding of how it all works.

    Then probably come up with a completely different method after that, as most of us do as well.. lol :)
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    Newsflash: CHATGPT CANNOT WRITE SOFTWARE.

    Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

    How to do tutorials properly, two (2) simple steps to success:

    Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That's how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.

    Fortunately this is the easiest part to get right: Be a robot. Don't make any mistakes.
    BE PERFECT IN EVERYTHING YOU DO HERE!!


    If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

    Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

    Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

    Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there's an error, you will NEVER be the first guy to find it.

    Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

    Finally, when you have errors, don't post here... just go fix your errors! Here's how:

    Remember: NOBODY here memorizes error codes. That's not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

    The complete error message contains everything you need to know to fix the error yourself.

    The important parts of the error message are:

    - the description of the error itself (google this; you are NEVER the first one!)
    - the file it occurred in (critical!)
    - the line number and character position (the two numbers in parentheses)
    - also possibly useful is the stack trace (all the lines of text in the lower console window)

    Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

    Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly?

    All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don't have to stop your progress and fiddle around with the forum.

    Imphenzia: How Did I Learn To Make Games:

     
  4. Fox-Random

    Fox-Random

    Joined:
    Dec 26, 2022
    Posts:
    4
    Well both answers are great but first one is just speed mode of doing effect without proper answering question.
    I dont know what I am doing wrong here:
    Code (CSharp):
    1.  private void OnCollisionEnter(Collision collision)
    2.     {
    3.         // actualDirection = collision.contacts[0].normal;
    4.         reflectedDirection = Vector3.Reflect(ballRb.velocity, collision.contacts[0].normal);
    5.         ballRb.velocity = reflectedDirection.normalized * speed;
    6.     }
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    The physics bounces your ball for you.

    What are you doing with all those computations?

    If you just want to enforce a constant speed after each bounce then just renormalize velocity in that collision function.

    Code (csharp):
    1. ballRb.velocity = ballRb.velocity.normalized * DesiredSpeed;
     
  6. Fox-Random

    Fox-Random

    Joined:
    Dec 26, 2022
    Posts:
    4
    Basicaly I fixed it: I keep actual velosity of a ball in fixedupdate and I make it equal to calculated velocity generated on Start and then After Collision it looks like that. I was making mistake because I was constantly recalulating reflect bounce from the beggining (Start) instead from when something acualy is happening. At least I am explaining it to myself like that. There is solved code for someone if wants to correct it or use it in future.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class BallMovement : MonoBehaviour
    6. {
    7.     private Rigidbody ballRb;
    8.     private float speed = 10f;
    9.     public Vector3 initialDirection, actualDirection, reflectedDirection;
    10.  
    11.     // Start is called before the first frame update
    12.     void Start()
    13.     {
    14.         ballRb = GetComponent<Rigidbody>();
    15.         initialDirection = genInitDirection();
    16.         ballRb.velocity  = initialDirection * speed;
    17.     }
    18.  
    19.     // Update is called once per frame
    20.     void Update()
    21.     {
    22.    
    23.     }
    24.  
    25.     private void FixedUpdate()
    26.     {
    27.         actualDirection = ballRb.velocity * speed;
    28.     }
    29.  
    30.     public Vector3 genInitDirection()
    31.     {
    32.         int x = (Random.Range(0, 2) * 2) -1 ;
    33.         float z = Random.Range(-1f, 1f);
    34.         Vector3 normInitDirect = new Vector3(x, 0, z);
    35.         return normInitDirect;
    36.     }
    37.  
    38.    private void OnCollisionEnter(Collision collision)
    39.     {
    40.      
    41.         reflectedDirection = Vector3.Reflect(actualDirection.normalized, collision.contacts[0].normal);
    42.         ballRb.velocity = reflectedDirection * speed; // Mathf.Max(refSpeed, 10f);
    43.     }
    44.  
    45. }
     
  7. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,082
    Seeing that you're not modifying the physics in FixedUpdate() there's no reason to do it in there. You should be able to move that line into OnCollisionEnter() before the other two lines.
     
  8. Fox-Random

    Fox-Random

    Joined:
    Dec 26, 2022
    Posts:
    4
    Thanks !

    WOW. My first personal task is done :)... after 2 days.... but experience is mine now :D
     
    Kurt-Dekker likes this.
  9. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    Don't forget to cement it or else it will be gone within a day or two and your time will be wasted.

    I use this process, as I posted above:

    Also, if you wanna check out my ultra-simple one-script
    Pong Solitaire, it is presently hosted at these locations:

    https://bitbucket.org/kurtdekker/pong_solitaire

    https://github.com/kurtdekker/pong_solitaire

    https://gitlab.com/kurtdekker/pong_solitaire

    Screenshot-KurtGame-133370265702819460.png
     
    Last edited: Aug 20, 2023
    wideeyenow_unity likes this.
  10. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    Very true, best I do is write a bunch snippet classes in NotePad++ detailing what my issue was, how I fixed it, and other suggestions on the same topic.

    However, if you forget to write your notes(like I do), you'll be right back where you started next time. :D
     
    Kurt-Dekker likes this.