Hey I am trying to calculate velocity of a gameObject without using rigidbody
https://www.youtube.com/watch?v=0v_H3oOR0aU&t=456s In this video, Brackeys adds velocity to the homing missile. The value he passes is transform.up * velocity
but what if I want to calculate velocity on my own how would I do that.
I tried the following code
void FixedUpdate ()
{
Vector2 target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = target - GetComponent<Rigidbody2D>().position;
direction.Normalize();
float rotationAmount = Vector3.Cross(direction, transform.up).z;
GetComponent<Rigidbody2D>().angularVelocity = -rotationAmount * rotationVelocity;
//GetComponent<Rigidbody2D>().velocity = transform.up * velocity;
Vector2 initialPos = transform.position;
Vector2 finalPos = (transform.position + (transform.up)) * Time.deltaTime;
Vector2 targetPos = finalPos - initialPos / Time.deltaTime;
transform.Translate(targetPos);
}
But the gameObject moves too fast and results in this error.
transform.position assign attempt for 'New Sprite' is not valid. Input position is { NaN, NaN, NaN }.
UnityEngine.Transform:Translate(Vector3)
Rocket:FixedUpdate() (at Assets/Rocket.cs:33)
Please help me just trying to implement basic physics in Unity. Also, I did check other questions but they did not help me I am still stuck.
Answer by AnkitR · Feb 16, 2020 at 06:18 AM
Figured it out...
using UnityEngine;
public class Rocket : MonoBehaviour
{
public float speed = 5f;
public float rotationVelocity = 2f;
public Transform target;
Vector2 velocity;
void FixedUpdate()
{
Vector2 desiredVelocity = (new Vector2(target.transform.position.x, target.transform.position.y) - (Vector2)transform.position).normalized;
desiredVelocity *= speed;
Vector2 steer = desiredVelocity - velocity;
velocity = Vector2.ClampMagnitude(velocity + steer * rotationVelocity * Time.deltaTime, speed);
transform.position += (Vector3)velocity * Time.deltaTime;
}
}
Your answer
Follow this Question
Related Questions
how do I find velocity relative to where my player is looking? 2 Answers
How do I get an object's velocity in one direction? 4 Answers
How to calculate velocity after collision? 0 Answers
Issue with impulse.magnitude and if statements? 0 Answers
How to use relativeVelocity to AddForce to the Rigidbody? 0 Answers