prevent entity from spinning

Discuss any questions about BEPUphysics or problems encountered.
Marvin
Posts: 32
Joined: Wed Aug 04, 2010 9:16 pm

prevent entity from spinning

Post by Marvin »

Dear Norbo,

Thankss for all the help so far, unfortunately a vehicle does not respond accurate enough to simulate the sledge. So I decided to come up with an idea to use 2 connected spheres, so no wheels only 2 spheres gliding down the hill. I'm locking the angular rotation so they will not roll down the hill.
My question is, how can I prevent or reduce the sideways sliding and redirect all the velocity in the forward direction to the new forward direction after i turn the sledge. So lets say the hill goes down in z-y direction with for every deltay/deltaz = 0.3/1.0. now the balls start of perfectly straight and go towards the z direction, I slightly rotate the sledge so the balls point to 0.9 z and 0.1 x, I want to redirect all the forward velocity in the z direction to the new 0.9z, 0.1x direction. How do I do this? I juggled some with the internal moment and internal velocity, but got not really bugproof results.

A slight drift is the disered effect offcourse but is not necessary.

And I need to test for each ball if it´s on the ground or not. How do I test this? With the wheels I could just check if the wheel had support.

thanks!
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: prevent entity from spinning

Post by Norbo »

Here's the general way you could get started:
1) Check to see if there's any contacts associated with the spheres (entity.collisionPairs.contacts)
2) For some contact, cross your object's forward direction with the contact point's normal direction to get your sliding direction. Normalize it. (slidingDirection = Vector3.Normalize(Vector3.Cross(contact.normal, entity.orientationMatrix.Forward)))
3) Compute the velocity of at the contact point (pointVelocity = linear velocity + angular velocity cross offset from center of mass to contact location).
4) Compute the sliding velocity (slidingDirection * Vector3.Dot(slidingDirection, pointVelocity)).

After that, it gets tricky. You might be able to get away with some sort of approximation and apply a corrective impulse using only the velocity and sliding direction, but to be 'correct' you need to compute the impulse that is required to bring the sliding velocity at that point to zero (and then you could soften or clamp it so that the sledge can slide some).

But, at that point, you'd basically be doing part of what the Vehicle wheel does internally. The vehicle also handles things in such a way that would be more robust than simply applying some impulses externally (which you could also do, but with significantly more work).

Object approximations that can't rotate are substantially simpler because the impulse computation comes down to dealing with the mass only rather than the inertia tensor. That's how the character controller works without getting too complicated.

Avoiding the vehicle and making a custom implementation can work, especially if you make a lot of simplifications. However, the vehicle should be capable of doing what you want, while saving a lot of time and effort compared to trying to implement something with equivalent features. I could assist with setting up/tuning the vehicle if you have some specific questions or issues.

And I need to test for each ball if it´s on the ground or not. How do I test this? With the wheels I could just check if the wheel had support.

You could check the entity's collisionPairs list. If the number of contacts in a collisionPair is greater than zero, then it's colliding.
Marvin
Posts: 32
Joined: Wed Aug 04, 2010 9:16 pm

Re: prevent entity from spinning

Post by Marvin »

thanks, I can work with that I guess

I did tested the vehicle class for about a week and tuned it the best I could, however it just does not respond to the real thing, not even close. And it should be a game so it should be fun to play and the steering is only a minor part and not very important, so I prefer to let the user focus on other things and make the steering easy.
So basically 2 balls sliding down the hill with a rotation around the y axis to steer works really well so far. Now I just have to put all the velocity generated in the forward direction. The vehicle class does this really nice, but I have to many issues with the vehicle being stuck, over responsiveness to bumps etc etc. the human body works as a single suspesion and just 2 balls sliding over the terrain mimic this back and forth movement to absorp small bumps a bit better for arcade like steering.
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: prevent entity from spinning

Post by Norbo »

The vehicle should be able to do at least as well as two spheres sliding along; in fact, wheels are extremely similar to contacts, except optimized for their specific purpose. They should be able to handle bumps better than their rigid contact counterparts, too.

Very simple steering can still be used with a vehicle. Without motorization and steering, vehicle wheels are basically just direction defined friction, which sounds like exactly what you want. Applying arbitrary rotation forces separate from the steering system is a perfectly valid approach, and is equivalent to steering without using the vehicle.

If you'd like, I can whip up a quick sample vehicle configuration (probably tomorrow). I just need to know what kind of base behavior you're looking for. From what I can tell, you're looking for something fairly arcadey that can slide forward and a little horizontally, but is resistant to rolling or generally uncontrolled movement. Any other information you can provide about the feel would help set it up.
Marvin
Posts: 32
Joined: Wed Aug 04, 2010 9:16 pm

Re: prevent entity from spinning

Post by Marvin »

Norbo wrote:Here's the general way you could get started:
1) Check to see if there's any contacts associated with the spheres (entity.collisionPairs.contacts)
2) For some contact, cross your object's forward direction with the contact point's normal direction to get your sliding direction. Normalize it. (slidingDirection = Vector3.Normalize(Vector3.Cross(contact.normal, entity.orientationMatrix.Forward)))
3) Compute the velocity of at the contact point (pointVelocity = linear velocity + angular velocity cross offset from center of mass to contact location).
4) Compute the sliding velocity (slidingDirection * Vector3.Dot(slidingDirection, pointVelocity)).
.


vehicle.body.collisionPairs.contacts remain empty while its obviously colliding with the ground. there is something wrong.

this should come close to the code right? (kk is a counter which unfortunately always displays zero)

foreach (CollisionPair collisionPair in vehicleInput.vehicle.body.collisionPairs)
{
if (collisionPair.contacts.Count != 0)
{
Vector3 slidingDirection = Vector3.Zero;
foreach (Contact contact in collisionPair.contacts)
{
slidingDirection = Vector3.Normalize(Vector3.Cross(contact.normal, vehicleInput.vehicle.body.orientationMatrix.Forward));
}
vehicleInput.vehicle.body.linearVelocity = slidingDirection * Vector3.Dot(slidingDirection, vehicleInput.vehicle.body.linearVelocity);
VehicleInput.kk = collisionPair.contacts.Count;
}

}
Marvin
Posts: 32
Joined: Wed Aug 04, 2010 9:16 pm

Re: prevent entity from spinning

Post by Marvin »

yeah I was looking to mimic the exact behaviour of snowboarding physics, like http://www.youtube.com/watch?v=HOSbt5iA ... re=related and http://www.youtube.com/watch?v=H4B-dZ6U ... re=related and
I had a pretty advanced vehicle with about 8 turning wheels all based up on the orientation of the board, which worked as it should but not on bumps. Since the human body is the suspension, the knees not the contact points itself like the wheels of the vehicle.

External force works best I think, since moving the center of mass is not exactly accurate. But I gave up on the realism with steering, as seen in those games, the board just remains flat on the ground even on little bumps it just sticks and the player does not get bumped out of the way or rolls over, the balls mimic this behaviour because they dont have a suspesion so they don't generate force to pop back like the wheels do.
I will make my model animated leaning left and right (in Maya) and just import it to fake the leaning, the balls or perhaps the vehicle will remain grounded for the best steering experience I think. 2 Wheels would be best I think, with an always upright position (I will fake "body rolls" in Maya as well). The second big problem I had with the vehicle is the need to have both wheel touching in order to steer, while I want the player to be able to always steer when grounded even if only the rear touches the ground to prevent oversteering while 1 wheel leaves the ground and comes back on the ground.

So in short: all contact points will remain on the ground (besides when jumping of course or going off a steep edge), steering whould just be a slight angular rotation (just the body rotated a bit to the right or left) then I would trigger the "lean animation" (just for the looks). When 2 wheels on the ground all x and z velocity will be root(x2 + z2) * new orientation after the rotation has happened, this should work fairly decent and will be good enough for my work, I think it will be easy to control without losing the need for a proper centered landing. (I can compare the landing Normal vesus the body orientation, if the error is bigger than such and so, trigger the pain/fall animation).

Hope I provided enough detail, it should be as simple as possible iot does not have to be fancy :) thanks for your time!
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: prevent entity from spinning

Post by Norbo »

vehicle.body.collisionPairs.contacts remain empty while its obviously colliding with the ground. there is something wrong.

That's probably because the object has gone inactive, and so the supporting triangles have disappeared. If you set the entity's isAlwaysActive property to true, then that won't happen.

The upcoming collision system rewrite will also change that behavior- contacts will persist on meshes even when inactive.

yeah I was looking to mimic the exact behaviour of snowboarding physics, like http://www.youtube.com/watch?v=HOSbt5iA ... re=related and http://www.youtube.com/watch?v=H4B-dZ6U ... re=related and
I had a pretty advanced vehicle with about 8 turning wheels all based up on the orientation of the board, which worked as it should but not on bumps. Since the human body is the suspension, the knees not the contact points itself like the wheels of the vehicle.

Those games probably throw out the idea of a physical board entirely in favor of what amounts to a character controller. While a vehicle could be made to deal with the bumpiness issues and all that, it's not really feasible to simulate all of the non-standard behavior. Robust sliding down a slope, turning, and jumping would be possible, but any sort of highly 'controlled' motion (tricks) would be much harder to implement.

So, to make something like that videos without a huge amount of work, the demos SimpleCharacterController is actually a good starting point. For example, try changing its acceleration field to 0, and its tractionDeceleration field to something lower than it is like 5-10, and maxSpeed to something higher (30?). Then, each frame, set the movementDirection field to the current 'forward' direction (on the horizontal plane, so just use the normalized x and z components). For testing, you can just try the camera's world transform forward vector.

That should let your character slide forward and back down slopes.

Here's an example implementation that I quickly did in the SimpleCharacterControllerInput class to set the movement direction. All I did was comment out the usual movement code in favor of always facing with the camera.

Code: Select all

                //Collect the movement impulses.

                Vector3 movementDir;

                //if (keyboardInput.IsKeyDown(Keys.E))
                //{
                    movementDir = camera.worldMatrix.Forward;
                    totalMovement += Vector2.Normalize(new Vector2(movementDir.X, movementDir.Z));
                //}
                //if (keyboardInput.IsKeyDown(Keys.D))
                //{
                //    movementDir = camera.worldMatrix.Forward;
                //    totalMovement -= Vector2.Normalize(new Vector2(movementDir.X, movementDir.Z));
                //}
                //if (keyboardInput.IsKeyDown(Keys.S))
                //{
                //    movementDir = camera.worldMatrix.Left;
                //    totalMovement += Vector2.Normalize(new Vector2(movementDir.X, movementDir.Z));
                //}
                //if (keyboardInput.IsKeyDown(Keys.F))
                //{
                //    movementDir = camera.worldMatrix.Right;
                //    totalMovement += Vector2.Normalize(new Vector2(movementDir.X, movementDir.Z));
                //}
                //if (totalMovement == Vector2.Zero)
                //    characterController.movementDirection = Vector2.Zero;
                //else
                //    characterController.movementDirection = Vector2.Normalize(totalMovement);
Marvin
Posts: 32
Joined: Wed Aug 04, 2010 9:16 pm

Re: prevent entity from spinning

Post by Marvin »

exactly! However will this still contain the proper way to land? and a natural way of fallig? Otherwise I could just calculate the landing normals vs the orientation of the character like I said and this should be fine I think.
I wanted to do the manual things, but I figured it could be just animations as well and not actually riding on the back of the board just "flat for collision" and manual animation with something like a water bubble which the player has to keep centered to kind of recreate the balance part of it all, and trigger a fall animation if the bubble reaches the left or right part like this thing http://www.onlinebouwmarkt.nl/winkel/im ... terpas.jpg (sorry english is not my first language and I dont live in an english speaking country so idk the word for it). To add a bit of realism.
I indeed figuered out a physics based character was a bit of an overkill, will this still function like a ball rolling of the hill? it will accelerate faster if the hill is steeper and will slow down if the hill is going "up"? Otherwise I could program this with some basic math and add a air resistance to control the maxspeed. or I could do maxspeed = maxspeed * steepnessHill f/e.

That demo is not included in the phone pack, I'll download the xbox version and port it, should not be too hard. Is there a demo which already uses these classes?

and in the air the camera rotation should remain it's yaw from before takeoff, and the character can be freely controllable barrel roll y-axis spin, back/front flip without rotating the camera (only translation). After the character touched the ground again the camera should follow the character again, this would just be setting the deltayaw to zero when there is no collision, this is how my vehicledemo class worked, and it looked really nice.
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: prevent entity from spinning

Post by Norbo »

However will this still contain the proper way to land? and a natural way of fallig?
The character controller can jump and fall like other things. The difference would be in handling the physical character entity's orientation; in a character controller, it's locked to simplify a lot of different calculations. Ideally, the actual character controller entity orientation would never be touched, and any rotation/tumbling from a bad landing would be handled separately (with maybe some extra deceleration to stop you from sliding as much when you've wiped out).

Also note that the character controller tries to 'glue' itself to the ground if it can for the purposes of stepping up/down obstacles. In the findSupport method, there's a section that sets the maximumDistance for a raycast (you can search 'glue' to find it). If you always use the maximumDistance = supportHeight option, the character will leave the ground more readily. The non-simple CharacterController also has a glueSpeed that can be configured if you want to incorporate that feature into the SimpleCharacterController.
it will accelerate faster if the hill is steeper and will slow down if the hill is going "up"? Otherwise I could program this with some basic math and add a air resistance to control the maxspeed. or I could do maxspeed = maxspeed * steepnessHill f/e.
Yes, it will slide faster down hills and decelerate when trying to go up hills. The SimpleCharacterController's maxSpeed field can be set to something like float.MaxValue so that it never tries to slow down your character (although I'd recommend something finite). Adding a 'drag' deceleration would be pretty simple, too.
Is there a demo which already uses these classes?
Almost every PC/Xbox360 demo can use the CharacterController. On the PC, it is activated by pressing 'C.' The SimpleCharacterController can be used instead of the CharacterController by replacing the references in StandardDemo.cs.
Marvin
Posts: 32
Joined: Wed Aug 04, 2010 9:16 pm

Re: prevent entity from spinning

Post by Marvin »

modified PlanetDemo

Code: Select all

 /*
      Copyright (C) 2010 Bepu Entertainment LLC.

      This software source code is provided 'as-is', without 
      any express or implied warranty.  In no event will the authors be held 
      liable for any damages arising from the use of this software.

      Permission is granted to anyone to use this software for any purpose,
      including commercial applications, and to alter it and redistribute it
      freely, subject to the following restrictions:

      1. The origin of this software must not be misrepresented; you must not
         claim that you wrote the original software. If you use this software
         in a product, an acknowledgment in the product documentation would be
         appreciated but is not required.
      2. Altered source versions must be plainly marked as such, and must not be
         misrepresented as being the original software.
      3. This notice may not be removed or altered from any source distribution.

    Contact us at:
    contact@bepu-games.com
 */


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using BEPUphysics.Entities;
using BEPUphysicsDrawer.Models;
using BEPUphysicsPhoneDemo.UIManagement;
using Microsoft.Xna.Framework.Graphics;
using BEPUphysics.DataStructures;
using BEPUphysics;

namespace BEPUphysicsPhoneDemo.Demos
{
    /// <summary>
    /// Shows a bunch of boxes floating in orbit.
    /// </summary>
    public class PlanetDemo : Demo
    {

        protected CharacterControllerInput character;
        protected Texture2D whitePixel;


        TriangleMesh mesh;
        public static Model map;
        public static Vector3 characterPosition;

        /// <summary>
        /// Gets the name of the simulation.
        /// </summary>
        public override string name
        {
            get { return "Snowboarding"; }
        }

        /// <summary>
        /// Constructs a new demo.
        /// </summary>
        /// <param name="game">Game owning this demo.</param>


        public PlanetDemo(PhoneGame game)
            : base(game)
        {
            // game.camera.removeInputEvents();
        }
        public override void initialize()
        {
            base.initialize();

            // game.camera.position = new Vector3(0, 5, 25);

            //Creates the player character (C).
            character = new CharacterControllerInput(game, space, game.camera);
            character.activate();
            
            game.modelDrawer.add(character);

            //Creates the Map
            StaticTriangleGroup.StaticTriangleGroupVertex[] vertices;
            int[] indices;
            StaticTriangleGroup.getVerticesAndIndicesFromModel(map, out vertices, out indices);

            mesh = new TriangleMesh(vertices, indices);
            mesh.worldMatrix = Matrix.CreateTranslation(new Vector3(0, 0, 0));
            StaticTriangleGroup group = new StaticTriangleGroup(mesh);
            space.add(group);
            game.modelDrawer.add(group);



        }
        public override void update(float dt)
        {

            base.update(dt); //Base.update updates the space, which needs to be done before the character or vehicle are updated.

            character.update(space.simulationSettings.timeStep.timeStepDuration);

            characterPosition = character.characterController.position;

        }

        public override void cleanUp()
        {
            //Wouldn't want the character or vehicle to own the camera after we switch.
            character.deactivate();

        }

    }
}

CharacterControllerInput

Code: Select all

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BEPUphysics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;

namespace BEPUphysicsPhoneDemo
{
    /// <summary>
    /// Handles input and movement of a character in the game.
    /// Acts as a simple 'front end' for the bookkeeping and math of the character controller.
    /// </summary>
    public class CharacterControllerInput
    {
        PhoneGame game;
        /// <summary>
        /// Physics representation of the character.
        /// </summary>
        public CharacterController characterController;
        /// <summary>
        /// Current offset from the position of the character to the 'eyes.'
        /// </summary>
        public Vector3 cameraOffset = new Vector3(0, .7f, -3);
        /// <summary>
        /// Camera to use for input.
        /// </summary>
        public Camera camera;
        /// <summary>
        /// Owning space of the character.
        /// </summary>
        public Space space;

        /// <summary>
        /// Whether or not to use the character controller's input.
        /// </summary>
        public bool isActive = true;


        /// <summary>
        /// Constructs the character and internal physics character controller.
        /// </summary>
        /// <param name="owningSpace">Space to add the character to.</param>
        /// <param name="cameraToUse">Camera to attach to the character.</param>
        public CharacterControllerInput(PhoneGame game, Space owningSpace, Camera cameraToUse)
        {
            this.game = game;
            characterController = new CharacterController(new Vector3(0,2,0), 3, 1, 20f, 1.4f, .01f, .04f);

            space = owningSpace;
            space.add(characterController);



            camera = cameraToUse;
            deactivate();

        }

        /// <summary>
        /// Gives the character control over the camera and movement input.
        /// </summary>
        public void activate()
        {
            if (!isActive)
            {
                isActive = true;
                // camera.useMovementControls = false;
                characterController.activate();
                characterController.body.teleportTo(camera.position);

            }

        }

        /// <summary>
        /// Returns input control to the camera.
        /// </summary>
        public void deactivate()
        {
            if (isActive)
            {
                isActive = false;
                // camera.useMovementControls = true;
                characterController.deactivate();
            }
        }

        #region Active/Inactive
        /// <summary>
        /// Handles the input and movement of the character.
        /// </summary>
        /// <param name="dt">Time since last frame in simulation seconds.</param>
        /// <param name="previousKeyboardInput">The last frame's keyboard state.</param>
        /// <param name="keyboardInput">The current frame's keyboard state.</param>
        /// <param name="previousGamePadInput">The last frame's gamepad state.</param>
        /// <param name="gamePadInput">The current frame's keyboard state.</param>
        TouchLocation originalTouchLocation;
        TouchLocation currentTouchLocation;


        bool touched(TouchLocation location)
        {
            if (originalTouchLocation.State == TouchLocationState.Invalid)
            {
                originalTouchLocation = location;
                currentTouchLocation = originalTouchLocation;
                return true;
            }
            return false;
        }

        bool released(TouchLocation location)
        {
            if (originalTouchLocation.Id == location.Id)
            {
                originalTouchLocation = default(TouchLocation);
                return true;
            }
            return false;
        }

        bool touchUpdated(TouchLocation location)
        {
            if (location.Id == originalTouchLocation.Id)
            {
                currentTouchLocation = location;
                return true;
            }
            return false;
        }
        #endregion

        public void update(float dt)
        {
            if (isActive)
            {
                if (originalTouchLocation.State != TouchLocationState.Invalid)
                {
                    
                    Vector2 offset = new Vector2((2 * currentTouchLocation.Position.X - game.GraphicsDevice.Viewport.Width) / (game.GraphicsDevice.Viewport.Width),
                                                 -(2 * currentTouchLocation.Position.Y - game.GraphicsDevice.Viewport.Height) / (game.GraphicsDevice.Viewport.Height));

                    //Jumping

                    if (offset.Y > 0.5f)
                    {
                        characterController.jump();
                    }
                    
                }

                //Note that the character controller's update method is not called here; this is because it is handled within its owning space.
                //This method's job is simply to tell the character to move around based on the camera and input.

                //Puts the camera at eye level.
                camera.position = characterController.body.centerPosition + cameraOffset;
                Vector2 totalMovement = Vector2.Zero;

                //Collect the movement impulses.

                Vector3 movementDir;
 
                movementDir = camera.worldMatrix.Forward;
                totalMovement += Vector2.Normalize(new Vector2(movementDir.X, movementDir.Z));
                

                

            }
        }
    }
}
Norbo, I modified the classes, and I changed the PlanetDemo to resemble the stardarddemo of the xbox demos.
It does not draw the map in space, nor does the thing jump or anything. There is something wrong in my code clearly. I dont know if I implemented it right. It's fairly similar to the standard demo from the xbox demos, yet it does not work at all, not even the drawing of the map.

EDIT: with my own drawer the map draws fine however the character does not slide of the hill it just stands still, and rotation and movement x-z don't work, it does fall from the sky (y direction) and lands on the map but than remains still, no sliding no moving.
Attachments
CharacterController.cs
(36.24 KiB) Downloaded 445 times
PhoneGame.cs
(17.29 KiB) Downloaded 432 times
Camera.cs
(9.23 KiB) Downloaded 432 times
Last edited by Marvin on Wed Aug 18, 2010 7:15 pm, edited 1 time in total.
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: prevent entity from spinning

Post by Norbo »

It does not draw the map in space
I believe the TriangleMesh should be added to the drawer, not the StaticTriangleGroup.
nor does the thing jump or anything
It can't jump without standing on something; make sure it's standing on something, and if it's not, make sure the gravity is set up right.

By the way, the CharacterController may work worse than the SimpleCharacterController for your purposes. It's more complicated and designed to handle stepping in a more powerful way, but that's unnecessary for snowboarding. The simplicity of the SimpleCharacterController makes it more robust and easier to understand.
Marvin
Posts: 32
Joined: Wed Aug 04, 2010 9:16 pm

Re: prevent entity from spinning

Post by Marvin »

oke thanks will try that later.

the true friction for a snowboard is 0.2 or around that region, sliding works beautifull with this value, 5-10 is just way too high.

But when it gets speed, it should only move in the direction of the character right? how can I get this done? because now the camera is facing forwards but whenever it hits a bump the camera starts to move in the x direction as well (which is not what we want, since we did not turn, it should only slow down in the z direction or go backwards).
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: prevent entity from spinning

Post by Norbo »

the true friction for a snowboard is 0.2 or around that region, sliding works beautifull with this value, 5-10 is just way too high.
Note that the deceleration values on the SimpleCharacterController are not coefficients of friction, but rather pure decelerations. A value of 5-10 for deceleration that fights side-to-side sliding could be necessary for controllable turns; 0.2 would probably be imperceptible and result in sliding around regardless of which direction you're facing.

You could technically modify it to use coefficients of friction, but decelerations tend to be pretty easy to tune since they don't care about mass.
Marvin
Posts: 32
Joined: Wed Aug 04, 2010 9:16 pm

Re: prevent entity from spinning

Post by Marvin »

when I set it to 5, the character does not move at all. While the hill is steep enough to make it slideable (it's about 30 degrees), I really don't get how the class works, do I have to apply a force or something to get the sledge going? To me its seems like the best solution would just be to keep the constant sideways velocity to 0, this in theory should move the object back in the camera direction right? Then I could just easily set the deceleration really low, if the sledge would turn, the sideways velocity would be zero and the velocity in the forward direction would be the old velocity.

Code: Select all

public void update(float dt)
        {
            if (isActive)
            {

                //Note that the character controller's update method is not called here; this is because it is handled within its owning space.
                //This method's job is simply to tell the character to move around based on the camera and input.

                //Puts the camera at eye level.
                camera.position = characterController.body.centerPosition + cameraOffset;
                
                Vector2 totalMovement = Vector2.Zero;

                //Collect the movement impulses.

                Vector3 movementDir;
 
                movementDir = camera.worldMatrix.Forward;
                totalMovement += Vector2.Normalize(new Vector2(movementDir.X, movementDir.Z));
                
                //Jumping
                /*
                if (previousKeyboardInput.IsKeyUp(Keys.A) && keyboardInput.IsKeyDown(Keys.A))
                {
                    characterController.jump();
                }
                */

            }
        }
If I'm not making a mistake, this does practically nothing right? is there something I'd have to do with totalMovement?
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: prevent entity from spinning

Post by Norbo »

It looks like there's a typo earlier in my code sample- you do have to set the character controller's movement direction (in the code sample I posted, the very last line should not be commented).

That probably explains the confusion. The deceleration will not to remove velocity that's along the character's movement direction. If it's not set, it's zero, which means all velocity is 'against' the movement direction, so it gets decelerated. If the movement direction is set properly, then tractionDeceleration will only fight against side-to-side motion.

Once it's properly set up, if the character is put on a slope, it will begin sliding down it.
Post Reply