- Home /
Question by
Major_Lag · Nov 18, 2019 at 07:27 PM ·
scripting problemvector2trackingtrigonometrymissile
How can I slowly rotate a vector2 to track a target and give velocity based on the angle.
I'm creating a little bullet hell for fun. I'm trying to implement a new oval ball that tracks the player and attempts to hit, like a missile. I have gotten the slow tracking all set however i'm having trouble turning the angle into the x and y components for a Vector2 to give velocity. Here is a picture representation of what is supposed to happen brought to you by Microsoft paint.
My code for MissileController:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MissileController : MonoBehaviour
{
public float speed;
public float turnSpeed;
Rigidbody2D rb;
Vector2 trianglePos;
Vector2 myPos;
Vector2 toTriangle;
float angle;
void Start() //start pointed at the player
{
trianglePos = GameObject.Find("Triangle").GetComponent<Rigidbody2D>().position;
rb = GetComponent<Rigidbody2D>();
myPos = rb.position;
toTriangle = trianglePos - myPos;
angle = Mathf.Atan2(toTriangle.y, toTriangle.x) * Mathf.Rad2Deg;
}
void Update() //keep track of and try to hit player
{
trianglePos = GameObject.Find("Triangle").GetComponent<Rigidbody2D>().position;
myPos = rb.position;
//slowly rotate to face player
toTriangle = trianglePos - myPos;
angle = Mathf.Lerp(angle, Mathf.Atan2(toTriangle.y, toTriangle.x) * Mathf.Rad2Deg, turnSpeed);
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
//take angle and get the x and y components
float x = Mathf.Cos(angle);
float y = Mathf.Sin(angle);
Debug.Log("Angle = " + angle + ", X = " + x + ", Y = " + y);
Vector2 trajectory = new Vector2(x,y);
rb.velocity = trajectory.normalized * speed;
}
}
missiles.png
(13.2 kB)
Comment
Best Answer
Answer by Naggil · Nov 19, 2019 at 10:05 PM
cant u just set the missile to move up with transform.up? if u are already rotating the missile there is no need to get a specific position to move on