- Home /
AddForce relative to child position and rotation?
Again a question.
I was thinking...
Is it possible to make the AddForce relative to a child on the object? Like position and rotation?
I've got the GameObject (Going to name it Motor) with this script:
using UnityEngine;
using System.Collections;
public class Rotation : MonoBehaviour {
public float Rotate = 10.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKey("b"))
transform.Rotate (Vector3.back * Rotate * Time.deltaTime);
}
}
And I want to apply its position and rotation to this AddForce :
GetComponent<ConstantForce>().GetComponent<Rigidbody>().AddForce (-transform.right * aPower * Time.deltaTime);
Is this even possible? If yes, Please help me.
Thanks for reading!
If this isn't possible then please tell me. Thanks -Coaster$$anonymous$$ind
Can't you just access the rigidbody through GetComponentInChild()?
No, Its not that easy. It needs to act like this link text
Will update my question soon with more and better info
Answer by toromano · Apr 22, 2016 at 12:16 PM
You need to apply relative force to the ship's rigidbody.
GameObject ship; //specify this
GameObject engine = ship.transform.GetChild(0); // assuming has only one rudder child
RigidBody shipRb = ship.GetComponent<RigidBody>();
shipRb.AddForceAtPosition(-engine.forward, engine.transform.position); // assuming blue axis is the engine direction
Hope that helps.
using UnityEngine;
using System.Collections;
public class TestA : $$anonymous$$onoBehaviour {
public GameObject ship;
public Rigidbody shipRb;
public Component Child;
public GameObject engine;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
GameObject ship; //specify this
GameObject engine = ship.transform.GetChild(0); // assu$$anonymous$$g has only one rudder child
Rigidbody shipRb = ship.GetComponent<Rigidbody>();
shipRb.AddForceAtPosition(-engine.forward, engine.transform.position); // assu$$anonymous$$g blue axis is the engine direction
}
}
Like this? This give errors.
Ok. I guess you are new to unity.
Try this:
using UnityEngine;
using System.Collections;
public class TestA : $$anonymous$$onoBehaviour
{
Rigidbody shipRb;
Transform engine;
public float thrust = 10f;
// Use this for initialization
void Start()
{
engine = transform.GetChild(0).transform;
shipRb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
shipRb.AddForceAtPosition(-engine.forward * thrust, engine.transform.position);
}
}
Add this script to to ship gameobject
Well. Thanks for trying to help me but its uncontrollable. Direct when I launch the game the object keep gaining speed. Im very very thankful of your help.
Here the link to a test Click here
Also I think I might set this project to wait until I have more experience.
And yes. Im new to Unity and scripting.