Unity 2D box collider to call and run C# script - c#

I have a camera shake C# script that I want to run once the player triggers a box collider?
The camera shake code:
using UnityEngine;
using System.Collections;
public class CameraShake : MonoBehaviour
{
public Transform camTransform;
public float shake = 0f;
public float shakeAmount = 0.7f;
Vector3 originalPos;
void Awake()
{
if (camTransform == null)
{
camTransform = GetComponent(typeof(Transform)) as Transform;
}
}
void OnEnable()
{
originalPos = camTransform.localPosition;
}
void Update()
}

That's because you did not add the OnTriggerEnter, OnTriggerStay or OnTriggerExit ( depending of what you want to achieve ) function to the script.
For e.g:
void OnTriggerEnter(Collider other){
if(other.tag == "Player"){
// shake the camera here..
}
}
Don't forget to check the trigger box in the box collider.

Related

How to throw a ball that player picked up in Unity 2d project

I have a problem with writing a function that throws spawned ball by pressing a button.
So far, i could only instantiate the ball and it is affected by gravity.
I can not wrap my head arround, how in my code should i add a force to push it with some force. Right now it just plops in front of a player.
I tried to fiddle with .AddForce() on a ball rigidbody2D and still nothing.
I would greatly appreciate if someone could take a look at the code and guide me into some directcion on where to AddForce for ball to make it move?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerControl : MonoBehaviour
{
[Header("Player Atributes")]
[SerializeField] float runSpeed = 10f;
Vector2 moveInput;
Rigidbody2D playerRigidbody2D;
[Header("Ball Settings")]
public bool playerHasABall = false;
[SerializeField] GameObject ball;
[SerializeField] Transform ballSpawn;
void Start()
{
playerRigidbody2D = GetComponent<Rigidbody2D>();
}
void Update()
{
Run();
FlipSprite();
}
void OnMove(InputValue value)
{
moveInput = value.Get<Vector2>();
}
void OnFire(InputValue value)
{
if(!playerHasABall) {return;}
Instantiate(ball, ballSpawn.position, transform.rotation);
playerHasABall = false;
}
void Run()
{
Vector2 playerVelocity = new Vector2 (moveInput.x * runSpeed, playerRigidbody2D.velocity.y);
playerRigidbody2D.velocity = playerVelocity;
}
void FlipSprite()
{
bool playerHasHorizontalSpeed = Mathf.Abs(playerRigidbody2D.velocity.x) > Mathf.Epsilon;
if (playerHasHorizontalSpeed)
{
transform.localScale = new Vector2 (Mathf.Sign(playerRigidbody2D.velocity.x), 1f);
}
}
//Ball picking up script. It destroys the ball with a tag "Ball" and sets a bool playerHasABall to true
private void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Ball")
{
Destroy(other.gameObject);
playerHasABall = true;
}
}
}
So, i manage to fiddle with the .AddForce() method once again and i came up with a solution to my problem.
My OnFire script looks like this:
void OnFire(InputValue value)
{
if(!playerHasABall) {return;}
Instantiate(ball, ballSpawn.position, transform.rotation);
playerHasABall = false;
}
No change here. I made another script called "BallBehaviour.cs" and added it to the ball with a code like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallBehaviour : MonoBehaviour
{
[SerializeField] float ballForce = 20f;
PlayerControl player;
void Start()
{
player = FindObjectOfType<PlayerControl>();
Throw();
}
public void Throw()
{
GetComponent<Rigidbody2D>().AddForce(player.transform.localScale * ballForce, ForceMode2D.Impulse);
}
}
Basically, the method Throw() tells the ball to check the direction the player is facing and then multiply it by ballForce. Then, it uses the ForceMode2d.Impulse method to apply calculated force to the ball for a second and it works on left or right direction.
Thanks Jkimishere for a nudge in a propper direction!
You might need a variable to check if the player is facing right/left.
If the player is, just add force to the ball depending on the direction.
if(!playerHasABall) {return;}
Instantiate(ball,
ballSpawn.position,
transform.rotation);
//Check which way the player is facing and add forrce to that direction.
//Adding a FacingRight boolean might help.....
playerHasABall = false;

Audio Source in Unity ArgumentNullException

So I want to play an audio source when a collision trigger happens, but unity throws this exception:
ArgumentNullException: Value cannot be null. Parameter name: source
UnityEngine.AudioSource.Play () (at
<8e2857b79be4468ca1c28dda75978191>:0) PlanetMovement.OnTriggerEnter2D
(UnityEngine.Collider2D collision) (at
Assets/Scripts/PlanetMovement.cs:47)
This is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlanetMovement : MonoBehaviour
{
bool moveAllowed;
Collider2D col;
public float moveSpeed;
public GameObject restartPanel;
private AudioSource source;
// Start is called before the first frame update
void Start()
{
source = GetComponent<AudioSource>();
col = GetComponent<Collider2D>();
}
// Update is called once per frame
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
Vector2 touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
transform.position = Vector2.MoveTowards(transform.position, touchPosition, moveSpeed * Time.deltaTime);
}
}
public void GameOver()
{
Invoke("Delay", 1.5f);
}
public void Delay()
{
restartPanel.SetActive(true);
Time.timeScale = 0;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Asteroid")
{
source.Play();
GameOver();
Debug.Log("Hit");
}
}
}
The collision trigger works perfectly without the audio source. I don't know what's going on. The asteroids are a prefab spawned dynamically, if that's useful info.
Thank you.
My bad. Instead of creating an AudioSource component on the planet, I created a new AudioSource GameObject and then put it as a child of the planet. It's fixed
Sorry.

Object is not triggering collider

Hi my problem is in Unity, I am a beginner in c#, my gameObject is not triggering the collider that is set on the plane of the game, in order for it to reset it's position.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BasketballSpawnScript : MonoBehaviour
{
public Transform respawnPoint;
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Basketball"))
{
other.gameObject.transform.position = respawnPoint.position;
}
}
}
This script is attached to the plane and the gameobject is tagged with Basketball, when it enters the collider of the floor it should transform it's position to the original position.
I cannot see what is wrong, can I receive some help?
P.S I get this error when other gameobject go through the collider too.
NullReferenceException: Object reference not set to an instance of an object
If using a Transform for spawn point, remember to set the value of it in the inspector menu.
public Transform respawnPoint;
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Basketball"))
other.transform.position = respawnPoint.position;
}
else
public Vector3 respawnPoint = Vector3.zero;
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Basketball"))
other.transform.position = respawnPoint;
}
private void OnTriggerEnter(Collider other){
if(other.gameobject.tag=="Basketball"){
other.gameobject.transform.position = respawnPoint;
}
}
I hope it helps you.

Make object that destroy player

I writing simple game on Unity (C#)
I have player and want to make the destroyer, that will destroy player.
I create prefab of destroyer. And next, I create Quad.
I have spawn script:
using UnityEngine;
using System.Collections;
public class SpawnScript : MonoBehaviour {
public GameObject[] obj;
public float spawnMin = 1f;
public float spawnMax = 2f;
// Use this for initialization
void Start () {
Spawn();
}
void Spawn()
{
Instantiate(obj[Random.Range(0, obj.GetLength(0))], transform.position, Quaternion.identity);
Invoke("Spawn", Random.Range(spawnMin, spawnMax));
}
}
Also I write DestroyerScript:
using UnityEngine;
using System.Collections;
public class DestroyerScript : MonoBehaviour {
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
Application.LoadLevel(1);
return;
}
if (other.gameObject.transform.parent)
{
Destroy(other.gameObject.transform.parent.gameObject);
}
else
{
Destroy(other.gameObject);
}
}
}
My destroyer spawning, but when player get it, I don't have Game Over screen.
Add rigid body to both player and "player destroyer" and then set onTriggerEnter on your player destroyer like so:
void OnTriggerEnter(Collider other) {
Destroy(other.gameObject);
}
For some fine tuning, you can do some checks if the other object is in fact the Destroyer (you can compare the tag or something, I won't go into too much detail now).
EDIT: Uncheck "isTrigger" on your BoxColliders and try this:
void OnCollisionEnter (Collision col)
{
Destroy(col.gameObject);
}

Sound on collision

Can please someone format the code for me?
my code:
using UnityEngine;
using System.Collections;
public class ScorePoint : MonoBehaviour
{
private AudioSource audioSource;
public AudioClip Scored;
void OnTriggerEnter2D(Collider2D collider)
{
if(collider.tag == "Player")
{
audioSource = GetComponent<AudioSource>();
audioSource.clip = Scored;
audioSource.Play();
}
}
}
This code only works when the collider is Is Trigger.
If you want to make it work with a collider not set as a trigger you should use OnCollisionEnter2d instead. Make sure to change the parameter from Collider2d to Collision2d.
using UnityEngine;
using System.Collections;
public class ScorePoint : MonoBehaviour
{
private AudioSource audioSource;
public AudioClip Scored;
void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "Player")
{
audioSource = GetComponent<AudioSource>();
audioSource.clip = Scored;
audioSource.Play();
}
}
}
OnTriggerEnter2d
Sent when another object enters a trigger collider attached to this object (2D physics only).
http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerEnter2D.html
OnCollisionEnter2d
Sent when an incoming collider makes contact with this object's collider (2D physics only).
http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionEnter2D.html

Categories