user1919580
user1919580

Reputation: 151

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 to do something like the below, but then my object doesnt move 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));

Upvotes: 0

Views: 555

Answers (2)

RadiantMin3
RadiantMin3

Reputation: 113

You could set it as a parent but then you could have some problems with it so if you want do this instead:

When you start to pick it run this and store the offset on the object

public Vector 3 Offset = PickUpObject.transform.position - playerObject.transform.position;

then in the update method run this

transform.position = player.position + offset;

Upvotes: 0

axwcode
axwcode

Reputation: 7824

Make the Player the parent of the object.

obj.transform.parent = player.gameObject;

Then the object's position will always be relative to the Player's positio. When the Player moves, so too will the object.

Upvotes: 1

Related Questions