- Home /
How can I make this object relative to the players position?
The player in my game can levitate objects and move them around on the world xy with the mouse. How can I make the levitating object move with the player when he moves?
private void levitateObject() {
//Debug.Log("Levitating");
float yAxis = Input.GetAxis("Mouse Y");
float xAxis = Input.GetAxis("Mouse X");
Vector3 frontForce = playerCamera.transform.TransformDirection(Vector3.forward) * (yAxis * 1.5f) ;
Vector3 rightForce = playerCamera.transform.TransformDirection(Vector3.right) * (xAxis * 1.5f);
Vector3 currPos = levitatingObject.transform.position;
Vector3 nextPos = new Vector3 ( levitatingObject.transform.position, elevation, levitatingObject.transform.position) + rightForce + frontForce;
levitatingObject.GetComponent < Rigidbody > ().velocity = (nextPos - currPos) * 10;
}
I want do something like the below but then my object doesn't move at at all
Vector3 nextPos = new Vector3 ( transform.position.x + (levitatingObject.transform.position.x -transform.position.x) , elevation, transform.position.z + (levitatingObject.transform.position.z -transform.position.z));
Answer by Keita-kun · Jan 02, 2019 at 04:24 AM
Vector3 offset = new Vector3(0,1,2); //1 meter above the ground and 2 meters ahead
levitatingObject.transform.position = player.transform.position + offset;
Answer by mlnczk · Jan 02, 2019 at 02:17 PM
Do you have object's movement in FIxedUpdate method? You can also consider that whenever you grab an item and start to move it with your character - make it player's child in hierarchy. Therefore when you start to run it should move with you without using update method which is way more efficient. If you can grab an item with mouse move it and realease it for example on mouse release button then you can call all those actions and just simply put object as child and remove it afterwards. Cheers!
void OnMouseDown(){ // on press mouse button
levitatingObject.transform.parent = this.transform; //considering that this script is attached to player
}
void OnMouseUp(){ // on release mouse button
levitatingObject.transform.parent = null;
}