How to detect properly when the player can crush an enemy from above? - unity3d

This question is much more complex than it seems, here's why.
I have a player and the physic is enabled, in a 2D + 3D world.
The monsters have a sinusoidal movement = they go up and down, from right to left.
The player can only jump more or less high, but can't move right or left (like the dino game on Chrome when there's no Internet connexion).
After many unsuccessful attempts to detect if the player is above (it's not simply if (PlayerY - MonsterY) > 0 otherwise I wouldn't ask here), the best idea I came up with is to make two colliders in the monster: one for the "head", and one for the "body".
When the player hits only the head it can only be above (otherwise it's the body first), so it's an easy situation
When the player hits only the body it can only be below or on the sides, so it's an easy situation too
sometimes, it happens that the player hits both colliders.
So I'd like to check this after the FixedUpdate calculations.
If you read the execution order of the callback functions, there's no LateFixedUpdate: even though there's a LateUpdate, it's officially written that the developer should handle physics in FixedUpdate, and nowhere else.
What I've done so far is: when the OnCollision of monster head is called, just change a boolean, and same for OnCollision of the monster body. So after the OnCollisionXXX, like the documentation says, there's only one thing you can use: yield WaitForFixedUpdate.
I'd like to check those booleans and act according to their values in the yield WaitForFixedUpdate.
I can't find any valuable example on the net on how to do this. Any idea how to implement yield WaitForFixedUpdate in this situation? I'm stuck.

To the question
how to implement yield WaitForFixedUpdate
The yield is ment to be used inside of a Coroutine
yield kind of reads like "interupt the routine here, render the current frame and continue from here in the next frame."
e.g.
private void Start()
{
// Start the routine once
StartCoroutine(LateFixedUpdate());
}
private IEnumerator LateFixedUpdate()
{
// looks scary but is okey in a Coroutine
// as long as you yield somewhere inside of the loop
while(true)
{
// Continue after all FixedUpdate has been called on all scripts
yield return new WaitForFixedUpdate();
// do something
}
}

Related

Unity New Input System and Animations

I am creating a basic 2D fighter game and am trying to replace what was the old input system with the new input system. Because of this the old systems update would wait for buttons and then call appropriate functions when they were pressed. Movement was actually the easiest part, simply rigging a 1D Vector and then grabbing the float to use with movement, awesome. However the difficulty is in pressing keys to change things in the game. For example, I have an input 's' which should lead to the method Crouch(). This method changes the animation running and alters the hitbox to be shorter and tell the attack to use a smaller hitbox as well. A Stand() method is called on release of 's' to return everything to the way it is. I have my Player Input object set to 'Invoke Unity Events' which leads to the corresponding method needed. The problem is that even though these events are set to be push and release they are read as a toggle effect instead of press and release triggers(respectively). This does the same thing with my attack function because it forces the animation to play twice, one for pressing and one for releasing. Is there a fix for this or is this currently a bug? Edit: Here are some images to clarify and the code used to reflect everything happening associated with the Attack functionality. Let me know if anything else should be needed
public void Attack(){
anim.SetTrigger("attack");
StartCoroutine(wait());
}
IEnumerator wait(){
if(!isCrouched){
yield return new WaitForSeconds(1.3f);
SHitBox.enabled = true;
yield return new WaitForSeconds(.5f);
SHitBox.enabled = false;
}
if(isCrouched){
yield return new WaitForSeconds(1.3f);
CHitBox.enabled = true;
yield return new WaitForSeconds(.5f);
CHitBox.enabled = false;
}
}
Binding
Action
Think I figured it out. At least for the purposes of this specific thread. The answer was it was not my code. There is what I am going to call a bug in the new Unity Input System. Specifically there were three lines of code all simultaneously being hooked which caused three calls on my method. The fix was commenting out two lines of code. Here's the thread where this is solved, coincidentally found on GitHub help pages, heres the link:
https://github.com/Unity-Technologies/InputSystem/issues/959
the issue is listed as close but its still a problem for me, lol...
The only issue left is that the behavior of selecting the type of button press that I want to use is still acting funky. Mainly the inputs are still simply firing without listening to the type of input I want. I am basically just going to start searching through unity code to find where these choices have impact. If there are no comments/answers in 8 hours I'll accept my own answer because this has technically been answered, it just leads to another question.

Unity 3D: what is the correct way to detect that the collision has already been processed for another collision participant?

I have a class CollisionHandler which has the OnCollisionEnter method. Each collideable entity in the game has CollisionHandler as a component. So, when 2 objects collide the OnCollisionEnter method is called twice and it's ok because the damage and other things are processed as a result of touching object "B" by object "A" and vice versa.
In addition, each collision creates a flash effect and plays a sound of impact and of course, these effects are also played twice for each collision. Although it wouldn't be imperceptible to the player it doesn't seem to be correct anyway. In order to prevent it, I came up with the following solution: I save the current frame number in another collision participant so it will know that these effects have been played already by the first one.
private void OnCollisionEnter(Collision collision)
{
// Calculate the damage caused by `this.gameObject` to `collision.gameObject`.
// ...
// Play an impact sound and show a visual effect.
if (thisObject.CollisionFrameId != Time.frameCount)
{
otherObject.CollisionFrameId = Time.frameCount;
// play sound
// show hit effect
}
}
Although it works I'm not sure (I'm a novice in Unity) that it's the best practice and if so please suggest other possible solutions.
Note that I didn't ask "Why is OnCollisionEnter getting called twice?". I know why it happens. My question is about the other, though it does mention the name of the same function it still doesn't asks the same.
You could do a GetComponent on the other object with one of your scripts (or the same script) and set the RecentCollisionObject to the current script or gameObject (and maybe a given time frame just for additional safety (if only one triggers it, but not the other for some reason)).
On each collision you check if RecentCollisionObject is the other object (and if no more than ~0.01 seconds has passed). If true, you know that particular collision must already have been processed by the other object just now, so reset all values from that other object and do nothing else. So the next collision which occurs, no matter how soon, will do this cycle anew and work as expected.
This way you let only the first to trigger the collide code execute your code (like a sound). The point is that both collision events are ran in the same frame, so no matter which triggers first, you can prevent the second from running.
You can use the Unity Tag System, you tag action to occur when colliding with that specific tagged object.
As example:
internal void OnTriggerEnter(Collider other) {
if (other.gameObject.tag == "Oject Tag") {
this.GetComponent<AudioSource> ().PlayOneShot (objectTagSoundClip);
}
Just need a audio to play placed in game object.
Maybe you have 2 Colliders. If so you could check if boxcollider for example is colliding only. You could also try on Collision leave. Hope it helps.

Method for Back button not working when Time.TimeScale=0

I have written below code for Back button event.
void Update()
{
if (Input.GetKey(KeyCode.Escape))
{
SceneManager.LoadScene("PreviousLevel");
}
}
In almost all cases this is fine. But I have found a small issue. When the user pauses the game, this doesn't work. When the user pauses the game, I do Time.timeScale=0. Initially, I gave a thought of modifying pause method and instead of doing Time.timeScale=0, use a bool variable and modify other pause logic accordingly. But then I also realized that I have over 14 co-routines whose logic is heavily dependent on Time.timeScale and modifying those will take a lot of time. They are heavily dependent on time.timeScale.
I wanted to know, is there any other method where I can write back button logic and which is not dependent on Time.timeScale.
It should work, input polling in Unity is not dependent on the time scale.
Try by inserting a Debug.Log inside the condition, and you should see it in the console.
Watch out if you put the if inside FixedUpdate and not Update: in that case it won't work since FixedUpdate is completely skipped when time scale is 0.
However, if you want a "dirty" trick, you can slow the timescale to a very low number, without using 0, i.e.: 10e-8. But use it with a lot of care, since it can lead to unwanted behaviour.
Input is dependent on time scale: GetButton() works normally but GetAxis() works inconsistently, for example getting mouse movement with GetAxis() works as expected, but getting Horizontal and Vertical returns 0 when timeScale is 0. You can get around this by using Input.GetAxisRaw().
It should also be noted that any axis also counts as a button, so you can also use GetButton() on those but the return value will be bool instead of float.

Spawning a projectile in ImpactJS

Using the example code that came with ImpactJS, I am wondering what
{direction:this.lastPressed}
means. The code below refers to the player entity, when the 'attack' button is pressed.
Is 'direction' a method of some sort? I am guessing from this code, it is telling the projectile which way to travel based on the entity's direction, but I can't figure out how.
//attack
if(ig.input.pressed('attack')) {
if (this.weapon == 'projectile'){
// create a projectile
ig.game.spawnEntity('EntityProjectile',this.pos.x,this.pos.y,{direction:this.lastPressed});
}else{
// we simulate a sword with a very fast moving projectile with a limited range
ig.game.spawnEntity('EntitySword',this.pos.x,this.pos.y,null);
}
ig.game.sortEntitiesDeferred();
}
I decided to go back to basics with this and use the code for this game to base mine on. This is a lot more straight-forward, especially for the first time game developer.

Unity - Selective Collisions - Again

I know this subject has been discussed here a bunch of times already. But I'm stuck here.
I am developing a simple game where I have a few rigid bodies piled and a projectile is intended to hit those gameObjects.
But some of those rigid bodies are collectibles, elements that give points if hit with the projectile.
My question is: I need those collectibles to behave just like the other rigid bodies, but as a trigger for the projectile.
How can I do it?
Regards.
I'm not one hundred percent sure I understand what you want, but here is what I think you need to be doing.
Set a tag on the collectible called "Collectible"
And then in the code write the following
Void OnCollisionEnter(Collision other){
if(other.tag == "Collectible"){
CollectCollectible();
}
}
OnCollisionEnter is run whenever something collides with the object, checking a tag is far from the most effecient way of doing this, but it's probably the easiest.
I'm not sure if I understand you right. Attach a Script to the collectibles and let it implement OnCollisionEnter. If you don't know which ones are the collectibles at design time, you can do it at runtime via AddComponent <MyCollectibleScript> ().
Another (pretty dirty) way is to take different physic materials but this just for the sake of completeness.