Top-down (3D) rotate arrow projectile towards shoot position
Hello there, I'm working on a top-down game in which a player can shoot an arrow projectile which moves in the direction of the mouse. I've set the arrow object to have a rigidbody and rotated the object to be facing forward (pic A).
I'm attempting to rotate the projectile along it's Y-axis (as that's the one I have setup to rotate around the players movement directions) so the arrow will point towards the movement direction rather than how it is right now (pic B).
Code:
using UnityEngine;
using System.Collections;
public class Player: MonoBehaviour {
public GameObject arrowProjectile;
void Start()
{
}
void Update()
{
if (Input.GetButtonDown("Ability_1"))
{
Vector3 myPos = transform.position;
float dist = Camera.main.transform.position.y - myPos.y;
float x = Input.mousePosition.x;
float y = Input.mousePosition.y;
Vector3 dir = Camera.main.ScreenToWorldPoint(new Vector3(x, y, dist)) - myPos;
GameObject projectile = (GameObject) Instantiate(arrowProjectile);
Rigidbody rigidbody = projectile.GetComponent<Rigidbody>();
rigidbody.velocity = dir.normalized * 5.0f;
Vector3.RotateTowards(projectile.transform.forward, dir, 5.0f * Time.deltaTime, 0.0f);
}
}
}
Pic A:
Pic B:
Answer by NorthStar79 · Feb 01, 2017 at 07:45 AM
take a look at "transform.TransformDirection()" and "Transform.TransformPoint" and also Transform.InverseTransformDirection . you can find further details at unity script refence docs.
I've read over those docs before (and I did again) and I do not see anything talking about rotation of an object's transform. I have an idea of the concept of getting the position of the mouse, and using that to modify the projectile's Y rotation from where it starts using some sort of math formula but I'm not sure exactly what that formula would be.
well , just try to raycast from your mouse position , and get world x and z position that raycast hits. and use transform.LookAt for arrow rotation. this should be solve your problem . if i understand you correctly , if you couldn't get it work. let me know. wil try to add an example script on my free time
Honestly an example would be super helpful. I'm going to continue to try to figure this out for the next 20 $$anonymous$$utes or so then head to bed. $$anonymous$$aybe I should set all transform values to 0 (position / rotation) in the prefab to make it less confusing?
idk. that should work , just keep tweaking numbers , and also pay attention the "5" over here arrow.transform.LookAt(new Vector3(hit.point.x,5,hit.point.z)); you may want to tweak this number too.
Your answer
Follow this Question
Related Questions
Torque rigidbody toward desired rotation on two axes ignoring Y axes? 0 Answers
How to make a cube rotate while moving? 1 Answer
How do I get a Rigidbody to rotate in the direction it is moving? 0 Answers
Question about NavMesh and Rigidbody 0 Answers
Rotate rigid body with mobile joystick 0 Answers