Move In Camera Direction HELP

Hi, Unity Community! I’m working on a ball toss FPS game, where when the ball instantiates, it moves in an arc forwards. Now I’m trying to do the same thing when I rotate the camera to look in a different direction. How can I accomplish this? Thanks for any help! :slight_smile:

Trajectory.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Trajectory : MonoBehaviour {
    public float speed = 20f;
    public float distance = 10f;
    public float angle = 45f;
    public float angleSpeed = 20f;

    float curAngle;

    void Start(){
        curAngle = angle;
    }

    void Update(){
        angle = Mathf.Clamp (angle, -curAngle, curAngle);
        angle += Time.deltaTime * -speed;

        transform.position += transform.forward * Time.deltaTime * distance;
        transform.rotation = Quaternion.AngleAxis (-angle, transform.right * Time.deltaTime * angleSpeed);
    }
}

Instantiate Snippet.cs

GameObject obj = Resources.Load ("Prefabs/Primative Level Design/Tossable") as GameObject;

        if (Input.GetButtonDown ("Cannon") && canShoot) {
            GameObject clone = Instantiate (obj, Camera.main.transform.position + Camera.main.transform.forward * 5, Camera.main.transform.rotation);
        }

Well, the Camera got a Transform just like your ball. So unless there is something I’ve missing here, why can’t you just do the same?

Lets say that I do add Camera.main.transform.forward to the code. In update, the ball’s direction will always be controlled by the camera movement. It’ll loose its arc. If held in the Start, it’ll work kind of. It’ll shoot okay in the world’s forward direction, but when I rotate the camera and shoot in the opposite forward direction, it acts as if there is a force preventing it from shooting straight.

example

Vector3 fwd;

void Start(){
fwd = Camera.main.transform.forward;
}
void Update(){
 transform.position += (fwd + transform.forward) * Time.deltaTime * distance;
}

Take out the “+ transform.forward” in your Update method. Unless you’re going to rotate the ball in the direction it should go, this is pointing in the wrong direction and you should not use it.

(Rotating the ball isn’t a bad idea, of course, but in that case you don’t need fwd. Pick one solution and go with it; don’t attempt to do both!)

Thank you, however capturing the Camera’s forward at birth and adding it looses the ball’s arc (just moves straight in the camera’s direction), and leaving it at transform.forward leaves me with my initial issue. I’m not sure as to why the Angle Axis line is not working when changing the transform.forward to fwd.

Well, the way you’re doing that arc is very unusual. The more typical way is to just implement Newton’s laws, i.e., keep track of your velocity, and add a bit of downward velocity (Vector3.down * gravity * Time.deltaTime) to your velocity each frame. Then adjust your position with transform.position += velocity * Time.deltaTime.

So if you do that, all you have to do is get your initial velocity correct (which I think is what your “fwd” does now).

It could also be done by rotating the projectile as it moves, of course, but I think we’d need to back up and start over.

Yeah, I’m not the best mathematician lol. My initial idea was to have the ball shoot in the direction of the camera while looking upwards lets say 45 degrees, then rotate down to the minimum of -45 degrees. This would simulate an arc, but I guess I did it wrong…

Perhaps this blog post on arcing projectiles will help.

Thanks, but I have no idea how to convert this from a 2D format to 3D.

I posted a video of a game that demonstrates the end goal here. Looking at the footage, I guessed that throwing a ball in the direction of the camera according to the camera’s looking height was not that hard to make in Unity3D. I guess I was wrong…any further help would be appreciated.

It’s not that hard. I’ve given you two easy ways to do it. A third easy way (probably what’s done in the video shown) is to just use the physics engine. To review:

  • Implement Newton’s equations, which are very simple in a case like this (I sketched out how to do it on Friday).
  • Use the arc code from the blog post I suggested on Saturday (change “Vector2” to “Vector3” for 3D).
  • Use the physics engine (see almost any Unity tutorial anywhere).

Pick a method and focus on it; ask specific questions if you get stuck.

I actually have this for a projectile script now, but I’m back at the same issue, where I cannot shoot in the direction of the Camera.

cs.

void Cannon(){
        if (Input.GetButtonDown ("Shield")) {
            GameObject obj = Instantiate (Resources.Load ("Prefabs/Primatives/Projectile"), Camera.main.transform.position, Camera.main.transform.rotation) as GameObject;

            Vector3 v = new Vector3 (0, Mathf.Sin(angle * Mathf.Deg2Rad), Mathf.Cos(angle * Mathf.Deg2Rad));
            obj.GetComponent<Rigidbody> ().velocity = v * Mathf.Sqrt (range * Physics.gravity.magnitude / Mathf.Sin (2 * angle * Mathf.Deg2Rad));
        }
    }

If you want help, you really need to provide more details. It looks like the code above shoots in the direction of ‘angle’. What is angle? How is it related to the direction of the camera? What happens with this code, and how is that different from what you want?

Sorry, I’m just shooting around a lot trying to find a fix when I should really take a bit more time to work around it. So far, this is the closest that I have gotten:

Trajectory.cs

IEnumerator Trajectory(GameObject obj){
        float speed = 45f;

        obj.transform.position = Camera.main.transform.position + new Vector3 (2, -2, 4);

        float dist = Vector3.Distance (obj.transform.position, target.position);
        float vel = dist / (Mathf.Sin (2 * angle * Mathf.Deg2Rad) / speed);

        float Vx = Mathf.Sqrt(vel) * Mathf.Cos(angle * Mathf.Deg2Rad);
        float Vy = Mathf.Sqrt(vel) * Mathf.Sin(angle * Mathf.Deg2Rad);

        float duration = dist / Vx;

        obj.transform.rotation = Quaternion.LookRotation(target.position - obj.transform.position);

        float time = 0;

        while (time < duration){
            obj.transform.Translate(0, (Vy - (speed * time)) * Time.deltaTime, Vx * Time.deltaTime);
            time += Time.deltaTime;
            yield return null;
        }
    }

After the object is instantiated, the object clone is passed to this function like so: StartCoroutine (Trajectory (obj)); This script allows me to shoot a projectile at an arc/angle towards a target Transform that I have set to be a child of the MainFPS camera about 200 units to the front of it. The only thing is is that when the projectile reaches the target, I guess it “finishes” and just awkwardly stops and falls to the ground according to the Rigidbody Component added to it.

The ideal goal would be not to even have a target in the first place so it just won’t stop, and to just fire in the direction of the camera while keeping its arc, speed, and mechanic to increase/decrease arc when I look upwards/downwards.
Sorry if it sounds complicated, it’s not quite easy to explain this kinda stuff to someone who hasn’t seen it. If you have any more questions just let me know. I really appreciate the help!

OK, the first thing you must decide is: are you going to move this object via physics, or move it via its Transform? Don’t attempt to do both (as you’re doing now). Pick one or the other.

For a task like this, both approaches are about equal complexity (i.e., both pretty simple). I don’t care which you pick. Choose one and let’s focus on it.

You haven’t said, but I’m guessing that you want these balls to interact with the environment — bouncing off of walls, rolling to a stop after they hit the ground, etc. In that case you should use physics (option 3 of the three options I listed on Monday). And in that case, don’t try to move the ball yourself. Your only task is to launch the ball with the correct velocity. The physics engine will do everything else. So your code should have no Coroutine, no while loop; nothing but instantiating it, and setting the velocity.

I gather you want this initial velocity to be a bit “up” from whatever direction the camera is pointing in. That’s easy enough to do; the camera has a Transform, and Transform has a TransformDirection method for just such an occasion. So your LaunchBall method should look something like this:

    [Tooltip("How fast the ball goes upon launch")]
    public float launchSpeed = 45f;
   
    [Tooltip("What direction to launch in, relative to camera forward")]
    public Vector3 launchDirection = new Vector3(0, 0.7f, 0.3f);

    void LaunchBall(GameObject obj) {
        Rigidbody rb = obj.GetComponent<Rigidbody>();
       
        rb.velocity = Camera.main.transform.TransformDirection(launchDirection.normalized) * launchSpeed;
    }

So you instantiate your new ball, position it where you want it to appear, and then call LaunchBall on it. LaunchBall sets the velocity. And then you forget about it — the ball will fly off according to the laws of physics.

(You’ll then presumably need to add other code to make stuff happen when the ball hits something, or destroy it under certain conditions, or whatever… but get it moving correctly first.)

Please try this and report back how it works for you.

private Vector3 launchDirection = new Vector3(0f, .12f, .13f);
    void LaunchBall(GameObject obj){
        Rigidbody rb = obj.GetComponent<Rigidbody>();

        rb.velocity = Camera.main.transform.TransformDirection(launchDirection.normalized) * 45f;
    }

This works pretty well with such small lines of code lol but it seems as though when I shoot and rotate the camera, it only shoots towards the positive world axis. Could the values in the launchDirection be affecting this? Can it also affect the height of the arch?

First, don’t make launchDirection private. Leave it public, so you can easily tweak it in the editor (even while the game is running).

And yes, it affects the height of the arch. Right now you have it elevated about 45 degrees (the Y and Z components are almost equal). If you want it to arch higher, increase Y and/or decrease Z, so it points more upwards. And you can also adjust the launch speed (which should also be a public property, rather than a constant in your code, so you can easily tweak it in the editor).

I’m having a bit of trouble believing that this only shoots towards world +X, regardless of the camera rotation. We’re clearly transforming that direction with the main camera. The only way I can imagine that wouldn’t work is if you have more than one camera, and the camera you’re rotating isn’t Camera.main… which seems unlikely.

So, double-check everything; carefully try facing different directions, make sure you’re actually calling LaunchBall, etc. If you’re still stuck, then post back with some screen shots of your set-up and screen shots or video of what’s happening. In that case it’ll probably be something silly, that just needs a fresh pair of eyes to see it (we’ve all been there!).

It actually was something silly, and I should have know! I instantiated the projectile from the main camera’s position, which is inside the character controller. I guess the collisions made it a bit funky, so I just shifted the spawn point a bit further this way:

GameObject obj = Instantiate (Resources.Load ("Prefabs/Primatives/Projectile"), Camera.main.transform.position + Camera.main.transform.forward * 4, Quaternion.identity) as GameObject;

and it worked fine.

After tinkering with the values, I believe this’ll do(changing z values to make them faster and etc.), but there’s one final concern. Much like the video, the balls seemed to have a bit more weight to them; they fall to the ground faster. My projectiles shoot faster, but seems floaty and takes a bit of time to touch ground. Is there a way to tweak this?

You can of course adjust the physics properties of your rigidbody (weight, etc.). But also consider the scale, i.e., what “1 unit” in Unity coordinates corresponds to in physics units. By default everything is set up for 1 unit = 1 meter, so something like a tennis ball should be like 0.05 units across. If your world is set up much bigger, then things will look floaty because everything actually is bigger than it should be (yet still accelerating downward at 9.8 m/sec).

Interesting. Whenever I make levels or import models, I just eyeball it and scale objects relative to other objects in the game. This explains a lot, actually! I pretty much scaled the whole game down a bit and got very different results.The projectile was indeed too large(I think it was like 3+ units). So I scaled it down to 0.5(even though it’s supposed to be the size of a tennis ball, 0.05 was too small to work with). It seemed to do the trick, and I’ll scale it down more if I need more weight on it.

Everything does seem to be working fine though, thank you so much for your help, I’ve been battling this for nearly months and never knew it was this simple. If you have any more references or tips, please let me know; I’d appreciate them. For anyone who wants the finished product, here it is:

Cannon.cs

void Cannon(){
        Vector3 launchDirection = new Vector3(0f, cannonHeight, cannonRange);

        if (Input.GetButton ("Cannon") && cannonStamp < Time.time && canShoot) {
            GameObject obj = Instantiate (Resources.Load ("Prefabs/Primatives/Projectile"), Camera.main.transform.position + Camera.main.transform.forward * 2, Quaternion.identity) as GameObject;
            Rigidbody rb = obj.GetComponent<Rigidbody>();

            rb.velocity = Camera.main.transform.TransformDirection(launchDirection.normalized) * cannonForce;
            cannonStamp = Time.time + cannonCooldown;

            Destroy (obj, 6);
        }
    }
1 Like