Code Monkey home page Code Monkey logo

charactercontroller2d's People

Contributors

a-deluna avatar foobraco avatar jamiltron avatar jceipek avatar jellybit avatar prime31 avatar shielrp avatar sjoshbrown avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

charactercontroller2d's Issues

Sometimes the character shoots into the air upwards

I'm using CharacterController2D in my prototype and I've noticed that sometimes velocity.y shoots to 300+ and the character goes flying into nothingness. I haven't been able to reproduce it predictably but it happens fairly often and is usually when my character is moving to the right into a physics object.

I haven't changed the CharacterController2D code, is there any possibly known reason for this, or have you never experienced this?

Thanks for an awesome piece of resource!

ignoreOneWayPlatformsThisFrame + sloped one way platform = !!!SUPER JUMP!!!

I submit this bug in the form of a (low FPS, sorry) gif:

ignoreonewayplatformsbug

Pretty sure I know the issue, and I would submit a pull request but I am unsure as to how you want to approach the solution. In the DemoScene.cs example, when holding "down" on a sloped platform, we do not fall through it, but still get our y-velocity multiplied by 3 - so, if we also hit jump while holding down, since we get a jump y-velocity assigned before the "falling through platforms" y-velocity, then we launch way up into the air!

Entirely possible this is a feature, not a bug :D

Character doesn't Jump when going up slopes

First, thanks for this great script 👍

So, my jump script alters the controller y's velocity:

        controller.velocity.y += jumpHeight * -Gravity * deltaTime;     
        float maxVelocity = Mathf.Sqrt(2f * jumpHeight * -Gravity);
        if (controller.velocity.y > maxVelocity)
        {
            controller.velocity.y = maxVelocity;
            canJump = false;
        }

This enables the player to jump higher if she presses the button longer, and it is working fine, except when the character is going up in the slope...
The code I use to check the player is grounded and can jump is this:

        if (controller.isGrounded && !canJump)
        {
            isJumping = false;
            canJump = true;
            JumpTime = 0;
        }

It works for every situation, excepts when player is going up a slope...

In you code, there's a flag _isGoingUpSlope that you use to check this. I tried letting it public and checking it in my code above, but I still couldn't make it work =X

What am I doing wrong here? Or is some check in the going up slope that is making this issue?
Thanks

collision trigger's false positive

False positive OnTriggerEnter2D if trigger position on one line - zero coordinate and detector.
For example: take Spelunky from Non-Physics-Based Demo and set to position coordinate x:9.53 y:7.0
And Trigger set to position x:4.0 y:2.1
Now run project and have false positive collision

Fix : add init position for new HelperGO:
CharacterController2D.cs
method createTriggerHelper()
add line after create new PlayerTriggerHelper:
go.transform.position = this.transform.position;

View:
341: var go = new GameObject( "PlayerTriggerHelper" );
342: go.transform.position = this.transform.position;

Character Moving through above tile if going up slope.

capturar

If you have a situation like this and keep moving up in the slope, the character "ignore" the above collision.

I "fixed" that by adding this. (ps: don't know if is the "right" way of doing this)

capturar1

Thanks for the awesome script!

[Question] Physics2D line cast.

Hi,

I'm using Physics2D.Linecast to achieve enemies' line of sight but to make that work it needs a collider and I'm using non-physic version of the CC2D that has Box collider and it is disabled (since you use just it's dimension and calculate physics yourself)

I was wondering of enabling box collider is problamatic. I've enabled it and apparently it's working nevertheless but I thought asking it here just to make sure.

Thanks.

primeRaycastOrigins incorrectly shaping raycastOrigins

The first and final raycasts should be positioned _skinWidth away from their respective sides. Instead, the first raycast is too close and the last one is too far away. This can cause unexpected behavior depending on which direction you are traveling. Going uphill to the right is especially more prone to having issues when dealing with slopes.

verticalrays

The problem is caused by primeRaycastOrigins() at this line: modifiedBounds.Expand( -_skinWidth ); This function reduces the total width and height by _skinWidth, or to put another way cuts off half of _skinWidth from every corner. This needs to doubled, similar to how recalculateDistanceBetweenRays() currently works, like this: modifiedBounds.Expand( -2f * _skinWidth );

Whole tile OneWayPlatform?

Hi,

Currently in order to have OneWayPlatforms we should have 2D edge collders on an object but I'm making a retro platformer with a tool that lets me "draw" the tiles and it would be great if I could just set layer for the tiles I want to behave like OneWayPlatform and the would act this way.

So is there a way to have OneWayPlatform with normal box 2d colliders rather than 2d edge collider?

Thanks

Animation problem. Please help.

Hello prime31,

I seem to be having a problem with the code and wondering if you can help me out with it. I can send you the code to your email if you like. But the problem I'm having, is the the mecanim state machine. I know this is not a sophisticated setup or full use of mecanim but I really appreciate the setup. I've studied the code and notice that my idle state, attack state, and duck animations are conflicting with one another. When I try to duck or attack, the idle state seems to trump the other commands and stop their animations prematurely. I may have crammed my coding a bit but I tried scenarios as to set a paremeter that sets a trigger to attack and try to turn the idle state off until the attack animation is done but I do not quite know how to approach. Sorry for the detailed explaination but do you have any suggestions.

Main problem: Attack and Duck state conflicts with my idle state.
My attempts: set paremeter to turn off idle when character is ducking or attacking.
Conclusion: Do not know how to implement for my idle state to stop to allow another to begin.

F.Y.I. - I did follow the Youtube video and it helped tremendously, thanks for that tutorial.

Character snaps to ground when dropping onto sloped surfaces.

When using the CharacterController2D to move a character along angled platforms, the character will snap to the ground when moving down onto a sloped surface that is sloped down in the direction of movement if the surface is within the distance defined by the slopeCheckRayDistance.
screenshot 2015-04-30 13 58 08

My game makes extensive use of lightly sloped surfaces, and disabling the snap-to-ground feature entirely makes moving down longer slopes (especially moving quickly) prone to problems. Not sure what a good solution would be.

Horizontal movement set to 0 with very small vertical accelerations on slopes

I've narrowed the code issue down to these lines:

image

Essentially, there is a little hiccup while trying to ascend slopes moving horizontally and then trying to leave the slope (vertically, up in my case) with very low acceleration. It seems to set my horizontal speed to zero like it's calculating a wall collision.

The "Debug.Log("FUCKED")" is my code. ;P I'm sure I'm doing something wrong, but I thought I'd bring this up. ALSO, I'm not sure how to fix it yet.

Velocity always changing.

Hi,
When a character with this awesome script attached is standing still, if you monitor the velocity, you'll witness that it's constantly changing. I'm sure it's Y does it always but it's X does it sometimes as well, if you move the character a bit.

Is this normal?

My best guess is due to applying gravity, the y value is momentarily negative and then get fixed somewhere in CC2D when rays are cast and such.

I'm referring to non-physic version.

Thanks.

Can't ascend low hanging one-way platforms, possible fix included

If a one-way platform is placed just overhead of the character, they cannot jump completely through it.

To recreate place a one-way platform just above the player. They don't need to be touching, but it has to be close enough so that the initial jump velocity will collide them in the first frame of the jump.

Expected result is that the player passes through the one-way platform, then lands on it after the jump is complete. Observed result is that the player travels most of the way through the platform, then their jump ends much sooner than expected and they fall back to where they started.

onewayjumpsnap

This issue can be resolved by modifying this line in CharacterController2D.moveVertically:

if (isGoingUp && !collisionState.wasGroundedLastFrame)
   mask &= ~oneWayPlatformMask;

If you remove the wasGroundedLastFrame condition the platform behaves as expected. Was this condition included to allow one-way platforms with slopes? Or is it for something else I'm not aware of?

License is vague.

Hi, the license used states that it is non commercial but you say this in the readme:

"You are free to use the CharacterController2D in any and all games that you make. You cannot sell the CharacterController2D directly or as part of a larger game asset."

Making it seem like it's allowed in a game release, just not as an asset package. If that's the case can this please be clarified and added to the readme?

Thanks.

Falling through diagonal one-way platforms

One-way platforms seem to work great if they're flat, but if you rotate one to e.g. a 45 degree angle and then jump onto it from the side, you will often (but not always) pass right through.

Thanks for the library btw (and Trashman).

How to detect my player's collider ?

Hi,

I'm actually trying to make a platform wich detects when my player arrives on, so i tought to use "OnCollisionEnter2D" and i've seen that doesn't work. I tried different things but nothing works... Can anyone help me ? =)

How to detect collision in non-physic character controller?

Hi,
First of all, thank you so much, this helped our project so much so far.

Since the non-physic system doesn't use colliders, what's the proper way to detect whether if player has collided with something like a trigger or another object?

Same thing goes for detecting bullets that go into the player, how to detect them.

Thank you.

Loss of reference on script reload during runtime.

Hi,

whenever I change a value in a script, it causes Unity to reload (some scripts or all of them, not sure) and this causes the player's reference to get lost or something because my state machine's reference to player raises an exception stating that player's CC2D script componenet reference is missing.

Am I missing something here?

Moving jerky in Unity 5.1.1

Hi, Thanks for sharing this controller. I really love it.

Have you try this project in Unity 5.1.1? On DemoScene, player move too jerky. It will be clearly when you config Time.timeScale < 0.5

Trigger Issue

Does not work with triggers, tried adding a script with OnTrigger2DEnter but never get called, think its down to the setup in RigidBody2D and Interpolate.

Broken Movement using PhysicsControllerTester (Unity 4.5)

In the move method of CharacterController2D, there is a preprocessor that determines whether to use

rigidbody2D.MovePosition(transform.position + deltaMovement) ;

or

rigidbody2D.velocity = deltaMovement / Time.fixedDeltaTime;

for movement, based on if you are using Unity 4.5 or 4.6.

Assuming a gravity value of -25, the latter equation causes rigidbody2D.velocity to decrease by 0.5 per frame. However, MovePosition does seem to change rigidbody2D.velocity, so the controller's velocity member is always 0 when called by PhysicsControllerTester.

The consequence of this is that falling speed is always

0 += gravity * Time.fixedDeltaTime;

instead of

_velocity.y += gravity * Time.fixedDeltaTime;

and horizontal speed is always

Mathf.Lerp(0f, normalizedHorizontalSpeed * runSpeed, Time.fixedDeltaTime * smoothedMovementFactor);

instead of

Mathf.Lerp(_velocity.x, normalizedHorizontalSpeed * runSpeed, Time.fixedDeltaTime * smoothedMovementFactor);

Everything works if I set the velocity member manually based on deltaMovement, but that seems to defeat the purpose of using MovePosition. I'm not sure if there is a correct fix to this, or if I'm better off just using the pre-MovePosition way of moving characters with physics.

[Question] License Clarification

Hello, recently I discovered this CharacterController and it seems like it would suit my needs really well. However, when I read the license I'm just having a slight misunderstanding. My question is would it be within the bounds of your license to use your controller in a non free game I'm making?

Descending from OneWayPlatform

In some games, which allows player to jump-down / descend (usually by pressing down + jump).

The way which I have implemented such functionality is by adding a new optional arg to:

private void moveVertically( ref Vector3 deltaMovement, bool descend = false ) {

and in the same method

if(descend)
    mask &= ~oneWayPlatformMask;

The descend boolean will be flagged as true whenever the player trigger the down+jump combo.

I wonder if there's any better way to implement this?

Stopping on slope knocks you backwards

If you stop moving up a slope and your velocity drops low enough without hitting zero, your deltaMovement.x can become smaller than _skinWidth. If this happens, when handleHorizontalSlope() adjusts your deltaMovement.x by _skinWidth it will actually cause you to briefly move in the opposite direction.

Easiest solution is to zero out deltaMovement.x if it changes direction. However, I suspect that this code block can be removed entirely. A similar_skinWidth adjustment occurs in moveHorizontally() because the ray it uses is _skinWidth longer than the original deltaMovement.x. But that has nothing to do with handleHorizontalSlope(), which merely takes the original deltaMovement.x and adjusts using the slopeSpeedMultiplier. It appears to be correcting for something that was never part of the equation.

Tested using 45 degree slopes and a skin width of 0.02.

Issue with sprite facing and movement

Hello! I joined this site for the sole purpose of commenting here! First and foremost, I can't tell you how fantastic this controller is. I'm very new to creating games, and as I don't know much code and I'm trying to work from the ground up, this script accompanied by your informational YouTube video has helped me a lot.

*** EDIT ***
I've figured out how to make the character duck or look up in the direction he was facing by removing the '-' in front of the transfor.localScale code. Not sure why that works but it does.


A secondary issue I'm having is integrating the mechanim into the script. For a Crawl animation, I'd like to operate it in a mechanim parameter, such as if Duck = True AND Run = True, then Crawl. Does that make sense? Not sure how to combine that information into the script to get it to behave in the animator. Here's what I've got at the moment.

// Crawling --------------------------------------------------------------------------------------------
else if( Input.GetKey( KeyCode.DownArrow) && Input.GetKeyDown( KeyCode.RightArrow) )
{
normalizedHorizontalSpeed = .5;
if( transform.localScale.x < 0f )
transform.localScale = new Vector3( -transform.localScale.x, transform.localScale.y, transform.localScale.z );

        if( _controller.isGrounded )
            _animator.Play( Animator.StringToHash( "Crawl" ) );
    }

Thanks again for any and all insight you can give me into this. As I said, I'm completely new to scripting, and I'm attempting to you the groundwork you've laid out as my introduction.

Orient Character

Hi,

It would be great to have orientation of the player handled in this as well. To do this, I have had to modify the CharacterController2D script and add in a function to orient the player based on the angle of the slope they are on. Its not perfect, but works for what I need right now.
It would be nice to see the following:

  • Checkbox to enable/disable the orientation of the player
  • If the player jumps, they should not still be oriented to the last slope they were on, but instead spring back to the default orientation.

Colliders won't push from behind

Hi, sorry if this is somewhat noob, I'm still a beginner with this... but how do I get the rays to cast on all sides all the time so that if the character is pushed by a collider from behind it will actually get pushed normally instead of starting to climb the wall? Or is there an easier way?

Thank you!

Collision issues when character collides with corner of platform

I have the CharacterController2D script on a character. In my test level I have some 2d colliders that are set as the ground. If I jump diagonally into a corner of the collider with my character, my character clips through the platform like in the picture attached. I'm assuming this is because rays are sent out vertically and horizontally, and I'm hitting right on my character's corner.

Blue block on the right jumped and corner hit the platformer, causing him to clip through and get stuck within the platform.
capture

Strance cache

Hi,

CharacterController2D inherits from MonoBehavior and I suppose it has "transform" field in it and filled with reference to Transform component of the game object that this script is attached to, but there is a reference defined for this.

What is the reason behind this?

Broken in Unity 4.5.5+

This controller is outdated and no longer works, as far as iv'e tested with the physics demo, in versions of unity past 4.5.5. There is something wrong with the gravity and jumping. Disable 'use physics for movement' and it works 'fairly well' if your'e not using physics.

Can't walk up sloped onewayplatforms

In the Non-Physics demo I changed the angle of one of the one way platforms. Unable to walk uphill on the slope and the character falls through. Is this intended? If it's not intended then perhaps this could be an enhancement added as an option somewhere?

Some parts of the slanted one way platforms do work though.

Works on sloped one way:

  • Can jump up through platform
  • Can land on platform
  • Can walk downhill without issue
  • Can walk uphill a tiny bit (before falling through)

screen shot 2014-05-23 at 11 37 31 am
This is the example platform I changed. I set the layer to be onewayplatform. I can walk downwards on this platform without issue. Can land on the platform OK, but can't walk upwards on the platform.

Stackoverflow

Hi (whoops, I created it before writing something),

I'm using the (Non-Physics-)Demo as a base for the movement of my game on Unity 4.5. Thanks for that. But if I stay on the same spot for a few minutes, there's an error "stack overflow", the one ray is really long onto the ground and is stuck. Plus, the vertical velocity is stuck at -2,778.

I tried to look up why it is happening, looked generally at the vertical velocity - and it slowly stacks down because gravity is added constantly (gravity * Time.deltaTime). If you zoom in, you can also see the one raycast, when your player is grounded, jittering. It slowly begins to grow, when suddenly the stack overflow appears and unity can't follow up.

Character smooths before landing

I can't recall if this happened pre-Unity5, but when the character lands from a jump it smooths towards the ground.
You can replicate this by simply turning the camera follow script off and jumping,
memem

ta

fall through one-way platforms?

I'm trying to have it so my character can drop down through one way platforms by pressing the down arrow key. Many games with one-way platforms let you do this such as Mario, Kirby, Smash Bros, etc.

I was able to get the conditional working to see if I was standing on something in the "OneWayPlatform" layer, but I can't figure out how to get my character to fall through it. I tried both IgnoreCollision and IgnoreLayerCollision and neither seemed to do anything. My guess is that this has something to do with the layer mask inside the CharacterController2D script, but I have no idea how that works. I am stumped!

If anyone could explain to me how to do this or point me in the right direction that'd be great!

Characters cannot have their own collision layer as a platform mask

This is actually mentioned in the readme, so I'm not sure if this will ever be addressed, but I was hoping someone had a solution to the inability to give characters the same collision layer as platforms. I'd love to be able to make characters that can be used as platforms / jump on top of one another. I completely understand if this is outside the bounds of what you'd like this project to do, however.

Looking into it, I can't think of a clean way to make it happen, since the collision code relies on raycasts and I'm not aware of any method to selectively ignore some of the colliders in a layer without just getting all possible hits in a line and discarding those from the host.

Thanks for the great library!

Falling through edge collider when moving up slope issue

Hi, thanks for creating and sharing this controller - its great!

I ran into an issue when the character moves up an edge collider slope when the delta movement is adjusted using the Pythagoras method. At the handleHorizontalSlope() method, the delta y movement is calculated based on delta x and the current slope angle. However, this does not work on edge colliders when the projected point crosses and edge, resulting in the character falling through the edge:

delta_adjustment

I added a quick hack at the handleHorizontalSlope() which does another raycast check for the scenario above, not sure whether it is correct or covers all cases though:

if (deltaMovement.y < jumpingThreshold)
{
// apply the slopeModifier to slow our movement up the slope
var slopeModifier = slopeSpeedMultiplier.Evaluate(angle);

Vector2 delta = new Vector2();

// we dont set collisions on the sides for this since a slope is not technically a side collision

// smooth y movement when we climb. we make the y movement equivalent to the actual y location that corresponds
// to our new x location using our good friend Pythagoras
delta.x = deltaMovement.x * slopeModifier;
delta.y = Mathf.Abs(Mathf.Tan(angle * Mathf.Deg2Rad) * delta.x);

var isGoingRight = deltaMovement.x > 0;

// check whether we go through a wall, if so adjust...
Vector2 ray = isGoingRight ? _raycastOrigins.bottomRight : _raycastOrigins.bottomLeft;
RaycastHit2D raycastHit;
if (collisionState.wasGroundedLastFrame)
raycastHit = Physics2D.Raycast(ray, delta.normalized, delta.magnitude, platformMask);
else
raycastHit = Physics2D.Raycast(ray, delta.normalized, delta.magnitude, platformMask & ~oneWayPlatformMask);

if (raycastHit)
{//we crossed an edge when using Pythagoras calculation, so we set the actual delta movement to the ray hit location
delta = raycastHit.point - ray;
if (isGoingRight)
{
delta.x -= _skinWidth;
}
else
{
delta.x += _skinWidth;
}
}
deltaMovement.y = delta.y;
deltaMovement.x = delta.x;

_isGoingUpSlope = true;

collisionState.below = true;
collisionState.lastTimeGrounded = Time.time;
}

Maybe have a look and see whether this is a valid issue and solution.

Cheers,
Roman

Quick adjustment in Camera Smooth Follow script

The camera offset is currently based on the Players velocity. I'd recommend to rely on the players local x scale (positive or negative). The current approach leads to problems on load and when the x velocity is zero. This has nothing to do with the controller itself, but it would be a nice adjustment for people that just wanna play around with it for a while.

Thank you for this amazing code!
Noël

Collision Detection

How exactly to I detect collision?
The OnCollision2DEnter method does not work with this!

Thanks in advance!

How to have triggers?

Hi,

I need to have triggers to detect when player (that is made with CC2D) passes a certain point but when I enable trigger of my BoxCollider2D, player won't pass through.

It seems that enabling or disabling the trigger check box on the collider doesn't have any effect.

I suspect it's due to CC2D only checking layers to have collision that is set to it's "Platform Mask" but how can I have a trigger functionality?

Am I missing something?

Thanks.

Weird motion when player get stuck inside blocks

untitled

If you have a situation like this, when the Black player get stuck inside platform, it will slowly rise up until standing on the top-most block. I don't get it at all so if you can guide my through this problem I'll be very appreciated.

*Edit: Collider on those blocks the player got stuck in is BoxCollider2D

Non-physics mode: not colliding with platforms?

I know physics-mode is broken now, but non-physics mode isn't working for me... my character is falling straight through my platforms, even though I've put my platforms on the 'platform' layer and put the 'platform' layer as the platform mask..

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.