Quantcast
Channel: Questions in topic: "addforce"
Viewing all articles
Browse latest Browse all 1264

Why does writing to rigidbody.velocity after AddForce stop my rigidbody moving?

$
0
0
I've not spotted this issue documented, so hoping someone can help out. My aim: 1. Add input force 'correctly' to my rigidbody (via AddForce) 2. Adjust the rigidbody velocity to stop it going too fast (e.g. by capping the max) [as an aside, I know for #2, adjusting the rigidbody velocity directly isn't recommended, but I still see it mentioned in Unity Answers and forums and it is even in some Unity demo scripts, I tried to only use it for limiting max velocity] I didn't even get as far as step #2 though - what I discovered was: After I use AddForce, then making *any* change to the rigidbody velocity, even just doing a get/set, seems to cancel out any movement made with AddForce. Any idea what I'm doing wrong? Have I missed something obvious? I'll paste my code below, you can repro by adding a cube and assigning this script to it. See the line marked #THEPROBLEM for whereabouts the issue occurs. using UnityEngine; using System.Collections; [RequireComponent(typeof(Rigidbody))] public class TestMover : MonoBehaviour { private Transform cameraTransform; void Start () { cameraTransform = Camera.main.transform; } public float charMoveInputForceXZ = 25f; void moveCharacter (Vector3 inputVector) { rigidbody.AddForce(inputVector * charMoveInputForceXZ * Time.deltaTime , ForceMode.VelocityChange); // #THEPROBLEM // The below should have no effect, yet... // * If commented out, the rigidbody can be moved // * If compiled in, the rigidbody cannot be moved // * If compiled in and placed prior to the AddForce line, the rigidbody can be moved Vector3 v; v = rigidbody.velocity; rigidbody.velocity = v; } void FixedUpdate () { Vector3 cameraForward; Vector3 moveInput = Vector3.zero; float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); if (cameraTransform != null) { // calculate camera relative direction to move: cameraForward = Vector3.Scale (cameraTransform.forward, new Vector3(1,0,1)).normalized; moveInput = v * cameraForward + h * cameraTransform.right; } if (moveInput.magnitude > 1) { moveInput.Normalize(); } moveCharacter(moveInput); } }

Viewing all articles
Browse latest Browse all 1264

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>