- Home /
How to connect a object to a moving player without messing its movement up
So i have this project that im working on and its a imple movement code attached to a sphere that rolls. I am trying to connect another object like a gun to it but the gun spins. I am trying to have it fixed in one position even when i move left, right etc. How can i connect the gun to the player?
this is a pic showing what i kinda want
Answer by Vicarian · Jun 14, 2017 at 05:25 PM
Parent the gun to the player object, then attach a script to it with an Update() method that inverts (cancels out) the parent's localRotation. For example:
using UnityEngine;
public class ExampleClass : MonoBehaviour {
Vector3 initialPosition;
void Awake() {
initialPosition = transform.localPosition;
}
void Update() {
transform.localPosition = Quaternion.Inverse(transform.parent.rotation) * initialPosition;
transform.localRotation = Quaternion.Inverse(transform.parent.rotation);
}
}
I forgot to cache the object's initial position and apply the inverse of the parent's rotation to it. I've updated my original answer.
Answer by Theby · Jun 14, 2017 at 05:29 PM
You can have this hierarchy:
Parent
- Ball
- Gun
So the parent is the one that moves and tells the ball to rotate. Since the Gun is not part of the ball it won't rotate, but it is part of the the parent so it will move.
Your answer
Follow this Question
Related Questions
Problem with Fuse/Mixamo Animations 0 Answers
Child of a player not syncing position with network? 0 Answers
How to let player know they have completed a level 2 Answers
Enemy wont damage player 2 Answers
Testing app on unity player that uses google sign in 0 Answers