Firstly hi to all! I am just trying to learn unity from basics. I am trying to write a code, shortly explain, golds and bombs dropping from the upside and we are trying to catch.
But in my code, bombs are fully working well but coins not working. Just nothing happening when coins touch my character. Coins have to destroy themselves and they must add +10 to my score.
Updated&Tested
For a 2D game, add a BoxCollider2D and a Rigidbody2D onto your character's GameObject. Set the coin object's BoxCollider's isTrigger bool to true in the inspector.
Add this to your player/character script.
int score = 0;
public UnityEngine.UI.Text scoreText; //in Unity, drag a text component here.
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Coin")
{
score += 10;
scoreText.text = score.toString();
collision.gameObject.SetActive(false);
}
}
For a 3D game, add a standard BoxCollider and a Rigidbody onto your character's GameObject. Set the coin object's BoxCollider's isTrigger bool to true in the inspector.
Add this to your player/character script:
int score = 0;
public UnityEngine.UI.Text scoreText; //in Unity, drag a text component here.
private void OnTriggerEnter2D(Collider collision)
{
if(collision.gameObject.tag=="Coin")
{
score += 10;
scoreText.text = score.toString();
collision.gameObject.SetActive(false);
}
}
Related
In my game on unity 2d I have spaceship and a planet. The planet is orbiting a star so I made a script that parents the planet to the player when I get within a range so the planet doesn't fly past or into the player. This script makes the player move with the planet so they land on it and fly around it easily.
Here is the script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ParentPlayer : MonoBehaviour
{
[SerializeField] GameObject Player;
private float Dist;
[SerializeField] float Threshold;
private CircleCollider2D ParentTrigger;
// Start is called before the first frame update
void Start()
{
ParentTrigger = GetComponents<CircleCollider2D>()[1];
ParentTrigger.isTrigger = true;
ParentTrigger.radius = Threshold / transform.localScale.x;
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collider)
{
if(collider.gameObject == Player)
{
collider.gameObject.transform.SetParent(transform);
}
}
private void OnTriggerExit2D(Collider2D collider)
{
if(collider.gameObject == Player)
{
collider.gameObject.transform.SetParent(null);
}
}
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, Threshold);
}
}
The problem is that as the planet rotates it ends up moving the player that has been parented to it. How can I make the planet's rotation not affect the position and rotation of the player, but still make the planets position affect the position of the player?
This might not be what you're looking for but I'm going to add it reguardless. Given that the Child-object will follow the parent, I would suggest putting the planet and spaceship as a child of the empty gameobject. Then you could rotate the the planet object, and if planets are in movement, you could add the movement to the parent object.
How about instead of parenting the player, write a script to set its position to the planets + some offset, and then the rotation wouldn't be an issue. Alternatively, if the player doesn't rotate at all, add constraints to its Rigidbody. Maybe something like this:
player.transform.position = planet.transform.position + offset;
Hope that works!
I'm a noob trying to make a game like this https://youtu.be/qxwO1wyz50w?t=37 , but i cannot figure out how to add collision to my line renderers. Would a line renderer be the way to go about this or is there a better way?
Here is my code so far (messy I know im new to programming as well )
public GameObject crossHair;
public LineRenderer line;
public Transform startPoint;
public GameObject lazer;
void Start()
{
Cursor.visible = false;
}
void Update()
{
crossHair.transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (Input.GetKeyDown(KeyCode.Mouse0))
{
LineSpawner();
startPoint.position = crossHair.transform.position;
}
}
void LineSpawner()
{
Vector2 shootDir = crossHair.transform.position - startPoint.transform.position;
GameObject lazerInstance = Instantiate(lazer);
line = lazerInstance.GetComponent<LineRenderer>();
line.SetPosition(0, startPoint.transform.position);
line.SetPosition(1, crossHair.transform.position);
Physics2D.Raycast(startPoint.transform.position, shootDir);
Debug.DrawRay(startPoint.transform.position, shootDir, Color.red);
}
Unfortunately, you cannot add a collider component to line renderers but a way around this is to create another gameobject that is invisible and make it a child of the line itself. What you then want to do is use the invoke("targetFunctionName", amountOfSeconds) method to destroy the collider gameobject after the player has hit it, this is so the game doesn't lag for those who are doing well while playing it. What you then want to do is add a physics material to the game object and set its bounciness property to max(which I think is 1). Do the same for the player's gameobject and you're done.
I have attached a script to a prefab and the script is:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class destroyer: MonoBehaviour {
Circles circles;
Collider2D collider1;
Collider2D collider2;
private void Start() {
collider1 = gameObject.transform.GetChild(0).GetComponent < Collider2D > ();
collider2 = gameObject.transform.GetChild(1).GetComponent < Collider2D > ();
circles = FindObjectOfType < Circles > ();
}
private void Update() {
if (transform.position.y < 2) {
Destroy(gameObject);
circles.instantiator();
}
}
void OnTriggerStay2D(Collider2D other) {
if (collider1.bounds.Contains(other.bounds.max) && collider1.bounds.Contains(other.bounds.min)) {
print("2");
if (other.bounds.Contains(collider2.bounds.max) && other.bounds.Contains(collider2.bounds.min)) {
print("3");
if (transform.position.y > 3) {
print("4");
Destroy(other.gameObject);
Destroy(gameObject);
circles.instantiator();
}
}
}
}
}
OnTriggerStay2D function is getting called but the condition when a GameObject is completely inside the collider 1 and outside the collider 2 is never true even if the other GameObject satisfies the condition.
Previously when I have attached both collider to the prefab then this condition becomes true when the game object satisfy the condition. But after the change it is not working. I think that I am not accessing the collider of a child properly or there is some other error. Please help me to resolve this problem.
This is the pic of gameobject with two children each having circular collider
and when other game object having circular collider comes in between both the circular collider then I want to perform some action.
this is ultimately what I want to achieve
Edit : the same function is working fine and I am getting what I want when I put the prefab on the scene and then running the game . But it is not working with the same prefab which is instantiated after running the game.
I think you can improve your conditions by using Collider2D.IsTouching like so:
void OnTriggerStay2D(Collider2D other) {
if (collider1.IsTouching(other)) {
print("2");
if (other.IsTouching(collider2)) {
print("3");
if (transform.position.y > 3) {
print("4");
Destroy(other.gameObject);
Destroy(gameObject);
circles.instantiator();
}
}
}
}
Reference: ScriptReference/Collider2D.IsTouching
Check whether this collider is touching the collider or not.
It is important to understand that checking whether colliders are touching or not is performed against the last physics system update; that is the state of touching colliders at that time. If you have just added a new Collider2D or have moved a Collider2D but a physics update has not yet taken place then the colliders will not be shown as touching. This function returns the same collision results as the physics collision or trigger callbacks.
EDIT 1:
You can also combine the previous code with: Physics2D.OverlapCollider
So you can do:
void OnTriggerStay2D(Collider2D other) {
if (collider1.IsTouching(other)) {
Collider2D[] results;
int elements = collider2.OverlapCollider(new ContactFilter2D, results);
if (elements > 0) {
// do some extra work with your result Collider2D array
// here
//
if (transform.position.y > 3) {
print("4");
Destroy(other.gameObject);
Destroy(gameObject);
circles.instantiator();
}
}
}
}
Is it possible to have two colliders for one object?
My situation is that I have a CircleCollider2D that causes my enemy to chase the player when it enters. This works well but I want to also have a BoxCollider2D that will switch scene to my scene called "BattleScene" when the player enters.
I want it so that when my player enters the circle collider my enemy will follow him but when the player gets closer and enters the box collider (both attached to the enemy) it will switch scenes to the scene called "BattleScene".
Another alternative I thought of was using a rigid body collision but I don't know how to implement that.
Here is my code
private bool checkContact;
private bool checkTrigger;
public float MoveSpeed;
public Transform target;
public Animator anim;
public Rigidbody2D myRigidBody;
BoxCollider2D boxCollider;
public string levelToLoad;
// Start is called before the first frame update
void Start()
{
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();//getting the position of our player
anim = GetComponent<Animator>();
myRigidBody = GetComponent<Rigidbody2D>();
boxCollider = gameObject.GetComponent<BoxCollider2D>();
}
// Update is called once per frame
void Update()
{
if (checkTrigger == true)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, MoveSpeed * Time.deltaTime); //move towrds from your position to the position of the player
if (myRigidBody.position.y < target.position.y && Mathf.Abs(target.position.y - myRigidBody.position.y) > Mathf.Abs(target.position.x - myRigidBody.position.x)) //if it is further away from target in x direction than y direction the animation for moving in y is loaded and vice versa
{
anim.SetFloat("MoveY", 1);
anim.SetFloat("MoveX", 0);
}
if (myRigidBody.position.y > target.position.y && Mathf.Abs(target.position.y - myRigidBody.position.y) > Mathf.Abs(target.position.x - myRigidBody.position.x))
{
anim.SetFloat("MoveY", -1);
anim.SetFloat("MoveX", 0);
}
if (myRigidBody.position.x > target.position.x && Mathf.Abs(target.position.y - myRigidBody.position.y) < Mathf.Abs(target.position.x - myRigidBody.position.x))
{
anim.SetFloat("MoveX", -1);
anim.SetFloat("MoveY", 0);
}
if (myRigidBody.position.x < target.position.x && Mathf.Abs(target.position.y -myRigidBody.position.y) < Mathf.Abs(target.position.x - myRigidBody.position.x))
{
anim.SetFloat("MoveX", 1);
anim.SetFloat("MoveY", 0);
}
anim.SetBool("checkTrigger", checkTrigger); //updating if in range
}
}
public void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.name == "Player")
{
checkTrigger = true; //setting our check trigger = true so it will follow if in radius
anim.SetBool("checkTrigger", checkTrigger);
}
}
public void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject.name == "Player")
{
checkTrigger = false; //setting our check trigger = false so it will not follow if not in radius
anim.SetBool("checkTrigger", checkTrigger);
}
EDIT: THIS PROBLEM HAS BEEN RESOLVED
The best way to handle this is by having an empty GameObject with the other collider attached to it, while making sure both GameObjects have a Rigidbody - the child with IsKinematic ticked. Why? Because this will separate the child GameObject from the parent collision structure. Read more about compound colliders.
You should only have more than one collider in one GameObject if they all make part of the same collision structure. If they have different purposes, use different GameObjects with kinematic Rigidbodies, each handling it's own task.
In your specific scenario, I would have the CircleCollider in the enemy itself and the BoxCollider in a child GameObject with a kinematic Rigidbody. This child GameObject can also contain a script with the sole purpose of checking against the Player and loading the BattleScene.
I have a small car game, and when I move up/down and left/right, the sprite becomes different. But the physicsbody remains the same. How do I adjust physicsbody? I added a screenshot of my sprite. At the moment I have Polygon physics body as on the right one.
Here is the code that adjusts animation states:
void FixedUpdate()
{
if (Input.GetKey(KeyCode.W)) {
rb2d.AddForce(Vector2.up * physicsConstant);
animator.CrossFade("CarUpIdle", 0);
} else if (Input.GetKey(KeyCode.S)) {
rb2d.AddForce(-Vector2.up * physicsConstant);
animator.CrossFade("CarDownIdle", 0);
} else if (Input.GetKey(KeyCode.D)) {
rb2d.AddForce(Vector2.right * physicsConstant);
animator.CrossFade("CarRightIdle", 0);
} else if (Input.GetKey(KeyCode.A)) {
rb2d.AddForce(-Vector2.right * physicsConstant);
animator.CrossFade("CarLeftIdle", 0);
}
}
To Change polygon based on sprite first you will need to have Serializefield variables to keep track of all the respective colliders. In this script basically what I do is I am keeping all the polygon colliders in array and iterate the array and enable it depending upon the sprite.
In the script im putting the required sprites along with the respective collider for sprite in sequence. So when I request the sprite to change I enable the respective collider and disables the other colliders. You will require something similer like this :
[SerializeField]
private Sprite[] Sprites;
[SerializeField]
private PolygonCollider2D[] Colliders;
private int index = 0;
private SpriteRenderer sp;
void Start () {
sp = GetComponent<SpriteRenderer>();
sp.sprite = Value[index];
}
void OnGUI() {
if(GUI.Button(new Rect(0,0, 80,35), "ChangeSprite")) {
colliders[index].enabled = false;
index ++;
if(index > Value.Length -1) {
index = 0;
}
sp.sprite = Sprites[index];
colliders[index].enabled = true;
}
}
Also in this tutorial it has been explained how to tackle this kind of problem
Unity Game Tutorial
Another way to proceed is to remove the ploygon collider and recreate it
Destroy(GetComponent<PolygonCollider2D>());
gameObject.AddComponent<PolygonCollider2D>();
though this is very bad programming considering I will be creating collider on every sprite change which is heavy on game.