I am struggling with a character parenting on moving platforms in 2D game.
I’m using OnTriggerEnter2D() for a detection when player steps on the moving platform. It changes his parent to that platform.
With common moving platforms (left-right) everything works fine, if a character stands on that platform he moves parallel with it, he can walk, jump etc.
The problem appears when I use the platform that hangs on two ropes connected with HingeJoint2Ds.
The player should swing that platform by walking left and right.
When using a keyboard input everything works fine but with a touch-input controller, when player doesn't move, the character remains on one place and doesn’t move with that platform. In a hierarchy panel is everything correct, player is a child of platform and the platform is moving but character isn't.
For moving character I’m using this: (part of character controller)
float move = Input.GetAxis ("Horizontal”);
rigidbody2D.velocity = new Vector2 (move * maxSpeed, rigidbody2D.velocity.y);
That’s the same for keyboard and touch input. Difference is only in the “move” variable getting.
The solution for moving and swinging platforms is same too. (hierarchy, parents, colliders etc.)
I am struggling with this for several hours but I have no idea what could be wrong.
Thanks for any help.
What do you call a "touch input controller", is it a touch device? If so, are you sure Input.GetAxis("Horizontal”) does anything on touch devices? won't it just return 0 always?
Have you tried logging your move value, or copying it to a public variable to watch it evolve in the inspector? Maybe the values are orders of magnitude apart between one controller and the other, in which case you would need a multiplier.
Related
I'm making a 2D platformer and decided to add sticky platforms. I've made the platforms move, but the player doesn't move with them.
However, after parenting the player to the platform, the player still falls through. I have added two BoxCollider2Ds and set one of them as a Trigger. None of the colliders have a RigidBody2D
public class StickyPlatform : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Player")
collision.gameObject.transform.SetParent(transform);
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.name == "Player")
collision.gameObject.transform.SetParent(null);
}
}
trigger does not stop object move through the box, you can try OnCollisionEnter.
Usually I would have a ground check and you can say if(isGrounded&&onPlatform) //move with platform
So it sounds you have two problems:
Player is falling through platform
Player isn't sticking to the platform
Falling through the floor is a super common bug, with many causes. Here is a checklist I found:
does Object have a Collider? If not, select Object
go to the top bar
components
physics
choose appropriate collider
(if Terrain, check the last tab, the little cog-wheel)
Note: mesh-collider may cause problems
Particularly, if both FallingObject and GroundObject have mesh-collider
Particularly, if the mesh is animated
To avoid mesh-collider, you can build an aproximate shape of your mesh from
several primitive colliders (in parent-, child- or sibling-GameObjects)
If you need a Mesh-collider no matter what, you can try to place additional primitive colliders where they won't be in the way to 'enforce' the collisions
Is the Object a Trigger? If so, select Object
find its Collider-Component (if Terrain, check the last tab, the little cog-wheel)
remove the check of 'IsTrigger'
Is the Collider placed well?
Fiddle with center, size and skin-width (start with 0.1) until the green outline aproximately fits the character
(If you get really strange values, it might be due to scale (e.g. your mesh was way too big so you downsized to .01))
You may try to zero out all positioning (both unity and your modeling-program)
The link goes into even more cases.
Once the player can stay on, the physics engine should handle the momentum transfer to move the player with the platform using friction. Which again, requires RigidBody2D. I'm not sure why you're not using RigidBodys, it kind of feels like you're avoiding the solution.
Doing it this way should avoid the need to parent the player, and have a trigger volume as well, unless you want the player physically stuck and can't move on the platform.
I recently started having a look at game development with Unity and was trying to make a simple 2D character with basic movement abilities. This character is supposed to jump and move from side to side, but only if it is standing on something.
Now my question is: How do you check if a player is standing on something? / Get the distance to the next game object / collider beneath the player game object?
Would greatly apreciate any helpful answers and especially explanations on how exactly it works. Thanks!
To do this, you need to send a ray to detect the point of impact on the ground and then calculate the distance. The code below sends a ray from the center of your object down to the maximum height (3) and gives the size.
public LayerMask groundLayer;
public float maxRayLength = 3;
public void Update()
{
var hit = Physics2D.Raycast(transform.position, Vector3.down, maxRayLength, groundLayer.value);
if (hit) Debug.Log(hit.distance); // it will print current distance from pivot
}
If you want to calculate the height of the ray from the character's foot, there are two methods, one is subtracting half the height of the character from it.
Physics2D.Raycast(transform.position-transform.up*height, ....)
Next one is to use an empty object at the base of the character, which we refer to instead of the center.
public Transform pivot;
Then..
Physics2D.Raycast(pivot, ....)
There are a few ways of actually doing this.
The most usual although a bit complicated way of doing it for a beginner is using Raycasts. A Raycast is basically a small invisible line that starts and ends where you tell it to. If anything of a specific tag or layer is caught in it's crossfire you can basically pull that object from your code. Raycasts are used for a lot of things, most notably in Shooter games to shoot or in games like Skyrim to pickup objects and interact with them.
Another way to do this, which is a bit more popular in 2D games is to create a "feet" GameObject and make it the child of the player in the hierarchy. You can add a box collider on that GameObject and check the "IsTrigger". You can add a Tag to your ground objects and through your code using the OnTriggerEnter() and OnTriggerExit() Methods you can basically tell when your character is floating on air and when he is on ground.
Another popular method is to use the Physics.OverlapBox() Method which is pretty much the same as the Trigger Method but you are creating an invisible box (much like a raycast) and instead of only getting notified when Triggered (something enters or exits) you check if the invisible box is colliding with another object/tag/collider (which could be your ground).
There are also a few different things you can do with a Nav Mesh (mostly in 3D) but I think that for now these 3 should suffice!
I am currently working on a classical fps game, I want to be able to generate larger numbers "enemies", ideally in the hundreds. Though this may not be feasible. I am hoping to use physics and Rigidbod[ies] for these enemy models.
Obviously the nice solution would be to have mesh colliders on all these models but I'm pretty sure that will affect performance. So my alternative idea was to instead set them up initially with box colliders while they are atleast X distance from the player and then once they enter that radius around the player to switch (via enabling and disabling) these box colliders to mesh colliders.
Is this possible to do and what are the implications? My initial tests caused the model to lose its collision detection with the floor, and so drop through the environment.
Are there are performance implications to switching (enabling/disabling) colliders/if this would even make a difference?
Lastly if none of the above, is there a better solution to this problem that is performant?
The most common practice I know is using multiple primitive colliders under the same rigidbody; I believe this is much more efficient than using mesh colliders, plus, as an added bonus you can even very easily handle special hits (headshots do x2 damage, leg shots slow enemies down) since you know exactly which collider was hit.
Here is an example of how they did it back in the day in Counter Strike
Notice that you will have to place each primitive collider correctly on the bone structure for it to move correctly during animations.
I think you should have two colliders for your ennemies :
1) A persistant box for physical interaction. (This collider would be on a separate layer, colliding only with the physical space.
2) Then, you would have your flexible box / mesh collider. Instead of swapping colliders, enable/disable them. If it is too far, try enabling the box, and if too close, enable the mesh collider. I think enabling and disabling is better for performance than removing and adding components at runtime. Plus, since you already have an 'environmental collider', swapping isn't an issue for the movement of your ennemies.
Hope this helps.
Ok, for this task I need to coordinate physics hitting a game object at a certain point and animation, to create the illusion of punching a character and he stumbles back as if propelled by that contact point.
I have rigid bodies on both the hitting object and character being hit, and can tell when the hitting object enters the character's box collider. What I thought to do first was create an impulse at the contact point then trigger my pre made character animation -
Vector3 direction = (this.transform.position - collider.transform.position) / (this.transform.position - collider.transform.position).magnitude;
this.transform.GetComponent<Rigidbody>().AddForce(direction, ForceMode.Impulse);
Problem is this just makes the character float slowly off opposite the hitting object (Rigidbody has gravity checked on character), and depending on where the character is facing, the animation looks not coordinated with the punch.
I wanted to see whether there's a streamlined way of doing this - how can I create a realistic punch/moving backward situation in Unity?
There's no easy way to get this behavior out-of-the-box with Unity. You will need to script a blending of ragdoll physics with animations.
One approach you might want to try is a system that "pins" your ragdoll to the bones of an animation, and if a collision occurs, the ragdoll unpins itself (partially or completely) from the bones, temporarily. When/if it completes being affected by physics, you would probably want to animate from a keyframe dynamically created based on the position of the ragdoll to a target keyframe.
There are also tools like PuppetMaster on the asset store that are meant to do things like this, but they are often not free, because they are difficult to make well.
I am working on a 3D unity project, which I have a platform in it and a character who runs on that platform, I placed the character on the platform but it started to fall down so I solved the problems by following these steps:
added a capsule collider to the object, it still fall through the platform
added a collider to the platform, then it didn't fall down but now these two objects are soled to each other so the character is just moving her legs in the same place,
Is there any way to make the character move on the platform while still using colliders?
Note 1: I made the collider trigger in the image to make the same exact behaviour with out colliders.
Note 2: I tried to put each one of them on a different layer but I get the same problem.
code:
void Update ()
{
rbody.velocity = new Vector3(rbody.velocity.x,0f,playerVelocity*Time.deltaTime);
rbody.transform.rotation = Quaternion.identity;
.
.
.
}
Making the collider trigger is like adding no collider. Trigger is only used when you want the collider to detect something but not stop it from running into things. So I believe you should add a non-trigger collider to both the character and the platform but make sure that the colliders are not intersecting when you put the character manually at first. If that didn't work, tell me exactly the coordinates of the character and the platform and the sizes of their colliders and I will try to replicate your scene to figure out the problem. Hope this helps!
Hi Friend you have 2 options...
Change the mass of your RigidBody
Use PhysicsMaterial and reduce the friction between the objects (Add a Physic Material to your Platform)
Increase the force and movement speed in your script.