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

Rigidbody add force relative to any rotation

$
0
0
Hi, currently my main camera holds the cube in front of it, and as I look around the cube rotates as i am turning. My script now only will shoot the rigidbody straight on the right mouse click if the camera is in such a position that the cube is rotated straight, aligned with the camera (player). How can i make this work when i look at any direction and the cube is turned in any rotation as i look and then I can press right mouse to shoot it forward in that direction? In my fixed update i currently am using transform.forward, which seems to only shoot it correctly when the rotation is near 0. Thanks! var currentObject : GameObject; var spawnTo : GameObject; var objectHeld : boolean = false; var force : float = 40.0f; @HideInInspector var lerpPosition : float = 0.0f; @HideInInspector var lerpTime : float = 2.0f; function Update (){ if (Input.GetMouseButtonDown(0)){ var hit : RaycastHit; var ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, hit, 8)){ if (hit.rigidbody){ currentObject = hit.rigidbody.gameObject; objectHeld = true; } } } if (!Input.GetMouseButton(0)){ objectHeld = false; lerpPosition = 0.0; } if (objectHeld){ lerpPosition += Time.deltaTime/lerpTime; currentObject.transform.position = Vector3.Lerp(currentObject.transform.position, spawnTo.transform.position, lerpPosition); currentObject.rigidbody.useGravity = false; currentObject.rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ | RigidbodyConstraints.FreezePositionZ; } if (!objectHeld){ currentObject.rigidbody.useGravity = true; currentObject.rigidbody.constraints = RigidbodyConstraints.None; } } function FixedUpdate ( ) { if (Input.GetMouseButtonDown(1) && objectHeld){ objectHeld = false; currentObject.rigidbody.AddRelativeForce(transform.forward * force); } }

Viewing all articles
Browse latest Browse all 1264

Trending Articles



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