0
\$\begingroup\$

I tried several approaches to get my sound working. This is one of them which most of the online tutorials showed me:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WallLeftSound : MonoBehaviour
{
    private AudioSource audioSource;
    public AudioClip Scored;

    void OnCollisionEnter2D(Collider2D collider)
    {

        if (collider.tag == "dot")
        {
            audioSource = GetComponent<AudioSource>();
            audioSource.clip = Scored;
            audioSource.Play();
        }
    }

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
    }

It's not working. Please note that this is work in progress, I tried several other approaches too. Thank you for you help.

enter image description here

enter image description here

Edit Dot:

public class Dot : MonoBehaviour
{
public float speed = 5;
public Transform spawnPoint;
public GameObject dot;
public AudioClip pongSound;
public AudioSource pongSource;


void Start()
{
    // Initial Velocity
    GetComponent<Rigidbody2D>().velocity = Vector2.right * speed;
    pongSource.clip = pongSound;
}

void Update()
{

}

float hitFactor(Vector2 ballPos, Vector2 racketPos,
                float PaddleRight)
{
    // ascii art:
    // ||  1 <- at the top of the racket
    // ||
    // ||  0 <- at the middle of the racket
    // ||
    // || -1 <- at the bottom of the racket
    return (ballPos.y - racketPos.y) / PaddleRight;
}


public void moveDot()
{
    gameObject.GetComponent<Rigidbody2D>().AddForce(Vector2.right * speed);
}
void OnCollisionEnter2D(Collision2D col)
{
    // Note: 'col' holds the collision information. If the
    // Ball collided with a racket, then:
    //   col.gameObject is the racket
    //   col.transform.position is the racket's position
    //   col.collider is the racket's collider

    // Hit the left Racket?
    if (col.gameObject.name == "PaddleLeft")
    {
        // Calculate hit Factor

        float y = hitFactor(transform.position,
                            col.transform.position,
                            col.collider.bounds.size.y);

        // Calculate direction, make length=1 via .normalized
        Vector2 dir = new Vector2(1, y).normalized;

        // Set Velocity with dir * speed
        GetComponent<Rigidbody2D>().velocity = dir * speed;
    }

    // Hit the right Racket?
    if (col.gameObject.name == "PaddleRight")
    {
        // Calculate hit Factor
        playSound();
        float y = hitFactor(transform.position,
                            col.transform.position,
                            col.collider.bounds.size.y);

        // Calculate direction, make length=1 via .normalized
        Vector2 dir = new Vector2(-1, y).normalized;

        // Set Velocity with dir * speed
        GetComponent<Rigidbody2D>().velocity = dir * speed;
    }

    if (col.gameObject.name == "WandRechts")
    {

        RespawnDot();
        GameObject.Destroy(gameObject);
        scoreScript2.scoreValue += 1;

    }

    if (col.gameObject.name == "WandLinks")
    {

        RespawnDot();
        GameObject.Destroy(gameObject);
        scoreScript.scoreValue += 1;
        pongSource.Play();




    }
}

Edit2 PlayerLeft

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerLeft : MonoBehaviour
{
private Rigidbody2D PaddleLeft;
[SerializeField]
private float movementSpeed;
void Start()
{
    PaddleLeft = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update()
{
   if (Input.GetKey(KeyCode.UpArrow))
        {
        PaddleLeft.velocity = new Vector2(0, 1 * movementSpeed);
    } 

  else if (Input.GetKey(KeyCode.DownArrow))

    {
        PaddleLeft.velocity = new Vector2(0, 1 *- movementSpeed);
    }

   else if (!Input.anyKeyDown)
    {
        PaddleLeft.velocity = Vector2.zero;
    }
}

private void HandleMovement()
{

}
}

Edit Picture BoxCollider enter image description here

\$\endgroup\$
  • \$\begingroup\$ We'll need to see your collider configuration — is either marked as a trigger? Also, what method are you using to move the ball? Have you verified whether the method is being called, but just not playing an audible sound, or is the method never called in the first place? \$\endgroup\$ – DMGregory Jan 9 at 13:06
  • 1
    \$\begingroup\$ From the screenshots, it seems you have not assigned the AudioClip "Scored" in the inspector. Assign that and see if it works \$\endgroup\$ – Aditya Yadav Jan 9 at 13:06
  • \$\begingroup\$ @DMGregory - No it's on 2D Collision which should work fine. But tried onTrigger which also didn't work. I edited with my Script for moving the dot. The method from what I saw in debug wasn't called at all. Audio is playing when set on "Play on Wake" \$\endgroup\$ – Redgrieve Jan 9 at 13:11
  • \$\begingroup\$ @AdityaYadav - I assigned "pingpong" in the inspector which I set for "scored" in the script via GetComponent. Not clean coding but I was just messing around and at this point I am kinda depressed for not knowing why it doesn't work. \$\endgroup\$ – Redgrieve Jan 9 at 13:11
  • \$\begingroup\$ For future reference, you can try adding a Debug.Log("my text"); on the same block as your sound-playing code, to make sure that it runs and prints that line. This would change the question to "Why isn't my collision working?" (Assuming it doesn't run after all, which is what seems to be happening) which is more accurate, and helps readers find the solution faster. \$\endgroup\$ – TomTsagk Jan 9 at 13:31
0
\$\begingroup\$

While I can not see how you configured the box collider of your "Wand Links", it seems to me like it would be a trigger-collider. This would make sense, because it seems to be a "kill zone" which removes the ball from the game and counts score. Those are usually implemented as trigger colliders.

  • Trigger colliders are non-corporeal (things fly through them). They call the Trigger-events on their behviours (OnTriggerEnter, OnTriggerStay, OnTriggerExit and their respective 2D versions).
  • Non-trigger colliders are corporeal (things crash into them). They call the Collision-events on their behaviours (OnCollisionEnter, OnCollisionStay, OnCollisionExit and their respective 2D versions).

For more information about which combinations of colliders and rigidbody settings cause trigger events and which cause collision events, see the collision tables in the Collider manual.

If I am right about the "Is Trigger" checkbox of the collider being marked, you need to use OnTriggerEnter2D instead of OnCollisionEnter2D.

Note that the trigger event methods take a Collider/Collider2D as a parameter, not a Collision/Collision2D.

Edit: Apparently the wall is not a trigger. But it also has no rigidbody and isn't marked as static, so it doesn't register collisions with rigidbodies either (check the collision matrix). Mark the "Is Trigger?" checkbox on the collider, use OnTrigger events, and it should work.

\$\endgroup\$
  • \$\begingroup\$ Wow thanks for that answer, really helped alot to understanding how it is supposed to work. I changed into (void OnTriggerEnter2D(Collider2D Dotcollision) { if (Dotcollision.tag == "dot") { Debug.Log("my text"); audioSource = GetComponent<AudioSource>(); audioSource.clip = Scored; audioSource.Play(); } } ) I hope this is what you meant and what I read in the manual. Sorry if I got it wrong I really tried to do as you told. I added the box collider to my topic. Code is a bit messy by now \$\endgroup\$ – Redgrieve Jan 9 at 17:16
  • \$\begingroup\$ @Redgrieve Ah, so the wall is not a trigger. But it also has no rigidbody and isn't marked as static, so it doesn't register collisions with rigidbodies either (check the collision matrix). Mark the "Is Trigger?" checkbox on the collider and it should work. \$\endgroup\$ – Philipp Jan 9 at 17:31
  • \$\begingroup\$ Hey, I am very sorry if it all seems a bit messy but as I said I tried several solutions and this is like my 7th try. After that I posted this question :D I updated the wall to "Is Trigger" If I do so, the dot just flys through the box instead of bouncing off of it. Wouldn't be a problem; I'd just lay a rigidbody below it. Problem is - sound still not playing. \$\endgroup\$ – Redgrieve Jan 9 at 19:35
  • \$\begingroup\$ I bought a book now to get into the topic step by step while still reading the manual. I'd like to thank you very much for your support - I'll mark the answer as the right one to get the topic closed. But if you have an idea regarding this problem I'd still be happy to get it solved. Thank you very much Philipp :) \$\endgroup\$ – Redgrieve Jan 10 at 11:31

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.