- Home /
How do I add force to the direction a game object is facing?
I want do apply physics force to a game object's rigidbody using Rigidbody.AddForce in the direction that another game object's transform is facing to. How do I do that?
This is a broken script as example of what I am trying to do:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
public class PushExample : MonoBehaviour {
public float strength = 1.0f;
public Transform direction = null;
void Update ()
{
if (this.direction != null && Input.GetButtonDown("action"))
{
this.rigidbody.AddForce(direction.rotation * strength);
}
}
}
Answer by robertbu · Apr 15, 2014 at 01:01 AM
Assuming you've setup your game objects so that forward of the object (direction object in this case) is the side facing positive 'z' when the rotation is (0,0,0), then you can do:
rigidbody.AddForce(direction.forward * strength);
Wow, how simple that was! I was having headaches trying to figure it out by myself =( Thank you!
If I have one object facing one way and I want to move another object based on the direction the first object is facing would I just use something like Vector3 direction = new Vector3(0, 0, firstObject.transform.position.z); ? I tried it in the context of
public void PushBackPlayer()
{
attackStart = Time.time;
while(Time.time < (attackStart + attackDuration))
{
pcControl.Simple$$anonymous$$ove(direction * Time.deltaTime);
}
}
and it crashed the Unity editor for some reason.....
Answer by mrck103 · Sep 11, 2017 at 10:32 AM
For me it was the Player cam, or the FPS camera. Just make a Public GameObject and put the FPS cam in it like this. ( this a script for my game its a force wand. As you hold down Left Click the force increases and when you let go the Force decrees.)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ForceThrowWand : MonoBehaviour {
public float range = 100f;
public float Times = 0.1f;
public Camera fpsCam;
public ParticleSystem ps;
public float delayOnParticle = 1f;
private float nextTimeToUse = 0f;
public float force = 1f;
void Update () {
if (Times <= 0) {
Times += Times;
} else {
if (Input.GetButton ("Fire1")) {
Shoot ();
} else {
if (force <= 1) {
} else {
force -= 0.1f;
}
}
if (Input.GetButton ("Fire1") && Time.time >= nextTimeToUse) {
ps.Play ();
nextTimeToUse = Time.time + 1f / delayOnParticle;
}
if (Input.GetButtonDown ("Fire2")) {
}
}
}
void Shoot() {
RaycastHit hit;
if (Physics.Raycast (fpsCam.transform.position, fpsCam.transform.forward, out hit, range)) {
hit.transform.GetComponent<Rigidbody> ().AddForce (fpsCam.transform.forward * force);
force += 0.1f;
}
}
}