How do I add multiple animators to my character - c#

I have my main character and added a capsule collider 2d so he would take damage when attacked. When the character is attacking, for example his body is out of the collider space and won’t take damage when hit. Please may you help me solve this issue, I’m very new to unity

One way of doing it is having two different hitboxes that does the same thing but with different shapes so they match two different states of your character.
Enable and disable them in a script when calling the attack using:
Public Collider2D attackCollider; //Drag your attack collider here in the inspector
Public Collider2D idleCollider; //Drag your idle collider here in the inspector
void AttackCollider() //call this fucntion to change to attack collider
{
attackCollider.enabled == true;
idleCollider.enabled == false;
}
void IdleCollider() //call this function to go back to normal collider.
{
attackCollider.enabled == false;
idleCollider.enabled == true;
}
If you want to I'm sure you can incorporate these two functions into an already existing attack function if you have one.

In 3D, you could simply make the Collider a child of any of your bones, it would get animated altogether.
But you mentioned Collider2D, so:
If you have a 2D Rig with bones, you can do the same as obove
If you have a Keyframe Animation, you could animate the collider to match your animation

Related

Detecting collisions in unity without actually applying force to the object

Hey so i am making a 2d game that is very similar to flappy bird (you jump when tapping the screen). The point of the game is to catch the green squares coming to you.
The problem i am encountering is that when my player hits the green square it seems to collide with it (it throws the player in some random direction or even stop into place like it hit a wall) even if on collision the green square is being destroyed.
So whenever the player hits the green square prefab it increments the score and destroys the square but sometimes when i jump right before hitting the square it stops like it collided with it insted of just passing right through.
The player prefab has got a rigidbody component and a 2d square collider.
The green square prefab has got only a 2d square collider component attached to it.
I am very new to unity and this is the first game i started developing.
If you need any further information please don't hesitate to ask.
Here is the player's rigidbody and 2d collider settings
Here is the green square's 2d collider settings
Maybe this picture of the gameplay can help. Imagine the blue square is the player and the green squares are the points you have to hit the red things are just the enemies that kill you so don't mind them. The player is standing still and the green square prefab have a script attached to it that adds a constant force to them. Hopefully this made it a lot clearer.
There is a really useful unity function that will detect when a collider touches another collider.
It is: void OnCollisionEnter(...)
You also have to pass in a Collider or Collider2d. So it will look like:
void OnCollisionEnter(Collider col)
or void OnCollisionEnter(Collider2D col)
Of course you have to have the necessary import statements for unity engine at the top as well.
You may want to use a trigger on your green Squares. then the bird is allowed to pass true but the square will activate your OnTriggerEnter code in your script.
so what you can try is:
public void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
//Run your code here!!!
//for example
Rigidbody rb = other.gameObject.GetComponent<Rigidbody>();
rb.AddForce(new Vector3(1, 1, 1));
}
}
this will add a force to your player/bird. but you can run any code in that method.
OnTriggerEnter and OnCollisionEnter run both when the object is hit by a rigidbody. but with OntriggerEnter you can pass thru the object. because it does not get effected by other physics objects. but onCollision usually does unless you freeze it in position.
side note OnTriggerEnter runs in FixedUpdate, so it is run at the end of each frame

Unity: Enemy objects passing through box collider on edges of background

I'm developing a simple 2D Unity game (which I'm very new to so sorry if this is a silly question!) in which my player can eat its enemies by colliding with them. This works fine as I'm just selecting the "is trigger" component for the enemies and using this code in my Player class:
private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("Hit detected");
Destroy(other.gameObject);
transform.localScale += new Vector3(x, y, z);
}
However, this means the colliders placed around the border of my background image aren't stopping the enemies. What's the best fix for this?
I don't understand very well your question. However it seems that your collisions are not working. So, remember that for have collisions actually taking place in your game you need to use colliders and that one of the two elements participating in the collision need to have the rigidbody component.
That will make the physics work in the engine, which triggers dont.
To check if that works you can debug with:
// called on collision
void OnCollisionEnter2D(Collision2D col)
{
Debug.Log("OnCollisionEnter2D");
}
From what I understood, you want only to detect triggers between the player and the enemies, but you still want these to collide with physic objects in your scene, such as background colliders.
One possible way to achieve this is to create a child object for the player object with a collider component with the trigger option set, and attaching a script to it to handle the triggers. Then, with the use of layers to group your player and enemy objects, you can uncheck the collision between them following: Edit -> Project Settings -> Physics 2D: "Layer Collision Matrix".
You can assign a script to any enemy, checking the distance with the player in each frame. Then you can Uncheck "is trigger"
Vector2.Distance

Unity: How can I programmatically solve an animated sprite with multiple colliders causing scoring issues?

I have an animated sprite which has 8 frames of animation. Each frame has a PolygonCollider2D attached as an element of an array thus providing it with accurate collision detection no matter which frame is playing.
When I had only one collider on the sprite and it passed through the "score" object the player's score increased by 1 point.
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Point")
{
score++;
scoreText.text = score.ToString();
return;
}
}
Polygon Collider 2D array in Unity inspector
Each collider in the array becomes active in turn...
public void SetColliderForSprite(int spriteNum)
{
colliders[batColliderIndex].enabled = false;
batColliderIndex = spriteNum;
colliders[batColliderIndex].enabled = true;
}
Now that each frame of the animation has its own collider I find that the score is increasing at an alarming rate as each frame plays multiple times whilst inside the "score" game object, triggering the point scoring logic multiple times, before the player leaves said object.
I'm wondering what the ideal programmatic solution is in order to ensure that on entering the "point" collider object the player only gets a score increment once before exiting the area?
Thanks in advance for any suggestions (and my apologies if this has been answered elsewhere).
EDIT: I was thinking about my post below and I think there is a simpler solution. You should be able to animate your collider shape rather than having 1 collider per animation frame. For example, see this question on How to update 2d colliders with sprite animation.
(And as a side note, you can also have multiple polygon colliders on each part of the sprite, and animate the colliders to move accordingly. For example, see this post on Animating Polygon Collider 2D. This alternative approach might make the suggestion I make in my post below simpler.)
One suggestion I have is to only increment the score when the first "Point" trigger is detected and then not incrementing the score again until the object has fully left. This can be implemented by keeping track of how many colliders (or which specific colliders) have entered and exited the object. Something like the following:
private const string PointTag = "Point";
private int _triggerCount;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == PointTag)
{
bool firstCollision = (_triggerCount == 0);
if (firstCollision)
{
score++;
scoreText.text = score.ToString();
}
_triggerCount++;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag == PointTag)
{
_triggerCount--;
}
}
However, once a collision is in progress, you will likely have to change the behaviour so that all colliders stay active until the object has fully left the collision area. This is because if you disable the collider, the OnTriggerExit2D event will not fire.
This solution may not be acceptable depending on how accurately you need to detect that the VampireBat has left the collision area.
If it doesn't need to be very accurate, you can simplify the solution by adding a 9th collider with a unique tag that covers the entire area of the sprite's animation. By using this 9th collider to determine when the player has left the collision area, you would not need to worry about affecting the code related to showing the appropriate collider per animation frame. (But note that the code example here would have to be modified so that the OnTriggerExit2D uses this 9th collider object.)
If it needs to be more accurate, I think there is likely a solution similar to what I suggested based on which colliders are currently active, the details of your collider shapes & animation frames, and OnTrigerEnter2D, OnTriggerStay, and OnTriggerExit2D. But note that you may also need to be careful that a collision is not re-triggered immediately. (For example, the object may have fully left the collision area, but the next animation frame might trigger a collision again immediately.)
Thanks for the response. Your edit got me to thinking about child objects. I added a child collider (with an index value of 9) then checked for a collision with that.
child object in inspector
Referenced the child collider in the collider array.
Collider array in inspector
After that it was just a matter of referencing it in the player controller script.
// Update is called once per frame
void Update () {
//Player input
if (Input.GetMouseButtonDown(0))
{
bat.velocity = new Vector2(0, 4);
//ADD BAT FLAP SOUND LATER!!!
}
scoreText.text = score.ToString();
Debug.Log("SCORE: " + score);
}
//Point increment function
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Point" && batColliderIndex == 9)
{
score++;
return;
}
}
I now have pixel perfect collision detection against obstacles and a score which increments correctly.
Thanks again.

Call upon multiple animation events on player

If I have a player and let's say a red ball hits my player and the player goes on fire... OK easy enough I did that. But now I want to add to the code below under the if statement that a blue ball hits my player and freezes or a black ball and causes death animation... But it's just not working out to add multiple animation events to 1 player.
Public GameObject GoneGo;
void OnTriggerEnter2D(Collider2D collisionObject)
{
if (collisionObject.gameObject.tag == "Orb")
{
PlayGone();
}
}
void PlayGone()
{
GameObject gone = (GameObject)Instantiate(GoneGo);
gone.transform.position = transform.position;
}
What you could do is perform a name check on the collider that impacts the player. You already have it checked the tag, have it check for redball,blueball, or blackball as the GameObject name afterwards.
You can handle multiple animations by looking into unitys mechanim system, which is the animator component (not animation component).
https://community.mixamo.com/hc/en-us/articles/203879268-Unity-Mecanim-Animation-Basics
What you would do after setting up the animator is have it SetTrigger for different trigger parameters. Or, you could use something like SetBool with a bool in the parameters like HitByBlueBall or HitByRedBall.
Hope this helps!

How to spawn a collider after exiting a trigger? (Bomberman style game)

I trouble trying to get this to work. here is the problem.
When I spawn I bomb with a collider, it presses my character out of the way, forcing him either in the wall or to a side.
Now my character instantiates a Bomb gameobject with a bomb script.
What I want and my thought process:
I was thinking it might be possible having a triggercollider on the instantiated bomb, and no collider, but when my character "leaves" the bomb radius it spawn a regular collider.
Then He can't get stuck, and when he has exited he can't just past through it again.
But I don't know how to write this, any suggestions?
Or any better ideas? Thanks for all help :)
ps: ( I use c#)
You almost get a solution.
1. in bomb collider check trigger;
2. in bomb script at start get reference to collider
3. in OnTriggerExit set isTrigger to false
public class bomb : MonoBehaviour {
BoxCollider collider;
void Start () {
collider = gameObject.GetComponent<BoxCollider> ();
}
void OnTriggerExit(Collider other)
{
collider.isTrigger = false;
}
}
P.S. don't mix 3d and 2d colliders. Code sample for 3d, in 2d it slightly different.

Categories

Resources