I'm trying to design a spitball/poison type projectile that will travel until it reaches the point clicked on screen and then destroys itself.
The problem is that contrary to what almost everyone says, Vector3.Movetowards is not moving the ball at a constant speed. If the target location is close to the launcher it moves slowly, if it is further away it moves much faster.
public float speed = 5f;
public Vector3 target = new Vector3();
void Update()
{
transform.position = Vector3.MoveTowards(transform.position, target,speed * Time.deltaTime);
}
Adding the launcher script
private void Shooting()
{
if (Input.GetMouseButton(0))
{
if (Time.time >= shotTime)
{
GameObject poison = Instantiate(Projectile, shotPoint.position, transform.rotation);
Vector3 target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
target.z = 10f;
poison.GetComponent<PoisonBall>().target = target;
shotTime = Time.time + timeBetweenShots;
}
}
}
Is the balls start position also at z=10f? Otherwise the difference in the speed most probably is a perspective issue in a 2D game and results in your bullet traveling in the Z direction but from your camera perspective you don't see that.
=> The closer you will be to the target the more movement will only happening on the Z axis, the further away the more movement is happening on X and Y.
Make sure to also do
var spawn = shotPoint.position;
spawn.z = 10f;
GameObject poison = Instantiate(Projectile, spawn, transform.rotation);
Or alternatively keep target.z = 0 (just remove the line target.z = 10f as per default the ScreenToWorld uses the Z component of given vector as depth and you are passing in a 2D vector with 0 depth anyway) and instead use Vector2.MoveTowards which will ignore ant depth on Z.
Related
I've been told that Rigidbody.MoveRotation is the best way in Unity 3D to rotate the player between fixed positions while still detecting hits. However, while I can move smoothly from fixed position to position with:
if (Vector3.Distance(player.position, targetPos) > 0.0455f) //FIXES JITTER
{
var direction = targetPos - rb.transform.position;
rb.MovePosition(transform.position + direction.normalized * playerSpeed * Time.fixedDeltaTime);
}
I can't find out how to rotate smoothly between fixed positions. I can rotate to the angle I want instantly using Rigidbody.MoveRotation(Vector3 target);, but I can't seem to find a way to do the above as a rotation.
Note: Vector3.Distance is the only thing stopping jitter. Has anyone got any ideas?
First of all MoveRotation doesn't take a Vector3 but rather a Quaternion.
Then in general your jitter might come from overshooting - you might be moving further than the distance between your player and target actually is.
You can avoid that bit by using Vector3.MoveTowards which prevents any overshooting of the target position like e.g.
Rigidbody rb;
float playerSpeed;
Vector3 targetPos;
// in general ONLY g through the Rigidbody as soon as dealing wit Physics
// do NOT go through transform at all
var currentPosition = rb.position;
// This moves with linear speed towards the target WITHOUT overshooting
// Note: It is recommended to always use "Time.deltaTime". It is correct also during "FixedUpdate"
var newPosition = Vector3.MoveTowards(currentPosition, targetPos, playerSpeed * Time.deltaTime);
rb.MovePosition(newPosition);
// [optionally]
// Note: Vector3 == Vector3 uses approximation with a precision of 1e-5
if(rb.position == targetPos)
{
Debug.Log("Arrived at target!");
}
Then you can simply apply this same concept also to rotation by going through the equivalent Quaternion.RotateTowards basically just the same approach
Rigidbody rb;
float anglePerSecond;
Quaternion targetRotation;
var currentRotation = rb.rotation;
var newRotation = Quaternion.RotateTowards(currentRotation, targetRotation, anglePerSecond * Time.deltaTime);
rb.MoveRotation(newRotation);
// [optionally]
// tests whether dot product is close to 1
if(rb.rotation == targetRotation)
{
Debug.Log("Arrived at rotation!");
}
You can go one step further and use a tweeting library to tween between rotations.
DOTween
With that you can call it like this:
rigidbody.DoRotate(target, 1f) to rotate to target in 1 second.
Or even add callbacks.
rigidbody.DoRotate(target, 1f).OnComplete(//any method or lambda you want)
If at some point you want to cancel the tween yuou can save it on a variable and then call tween.Kill();
So, you want to animate the rotation value over time until it reaches a certain value.
Inside the Update method, you can use the Lerp method to keep rotating the object to a point, but you will never really reach this point if you use Lerp. It will keep rotating forever (always closer to the point).
You can use the following:
private bool rotating = true;
public void Update()
{
if (rotating)
{
Vector3 to = new Vector3(20, 20, 20);
if (Vector3.Distance(transform.eulerAngles, to) > 0.01f)
{
transform.eulerAngles = Vector3.Lerp(transform.rotation.eulerAngles, to, Time.deltaTime);
}
else
{
transform.eulerAngles = to;
rotating = false;
}
}
}
So, if the distance between the current object angle and the desired angle is greater than 0.01f, it jumps right to the desired position and stop executing the Lerp method.
I am still a novice with Unity and am trying to make a top down 2D game and am stuck with the movement script where the movement is faster when I move diagonally. When I use normalized on the "axis" vector2 and start moving the player keeps moving for a bit and then stops moving suddenly when I stop pressing on any key and when I remove the normalized the movement goes back to normal and the player stops moving slowly and perfectly, but still when I move diagonally it is faster.
Here is my code:
{
Rigidbody2D rb;
Vector2 axis;
public float Speed = 400;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
movement();
}
void movement()
{
axis = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")).normlized * Speed;
rb.AddForce(axis, ForceMode2D.Force);
rb.drag = 60;
}
}
What happens is that the returned values of GetAxis are smoothed over some frames. So when you normalize the vector it returns a magnitude of 1 for a while even though your input is actually smaller than that since it is smoothing out.
In general instead of
new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical").normalized`
which always returns magnitude 1 also for smaller input you rather want to use Vector2.ClampMagnitude
axis = Vector2.ClampMagnitude(new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")), 1f) * Speed;
which only clamps if the vector has a total magnitude > 1
Im trying to simply get a ball to bounce with constant speed and without any infinite bounces. To avoid infinite bouncing I have added some drifting on each bounce in the collision event like this:
private void OnCollisionEnter2D(Collision2D collision)
{
Vector2 veclocityTweak = new Vector2(Random.Range(0f, 0.2f), Random.Range(0f, 0.2f));
rigigidBody2D.velocity += veclocityTweak;
}
I have also rotated the colliders (the ball is bouncing within this box)
This works ok. not perfect. But my real problem is that the ball suddenly stops and the rigidBody2D.velocity sets to (0.0, 0.0) as well as the magnitude.
I tried to prevent this by this function running in the update function checking the velocity. The idea is that it should prevent the ball to go to 0 in velocity but still that happens after a while:
private void checkVelocity()
{
Vector2 vel = rigigidBody2D.velocity;
float minSpeed = 0.8f;
if (vel.magnitude < minSpeed)
{
float multipl = Random.Range(-1.0f, 1.0f);
rigigidBody2D.velocity = vel.normalized * multipl;
}
}
Here is my settings in the Project Settings:
And I have set the material for the ball to:
How can I prevent the ball from stopping?
I would recomend doing this:
float minVelocity = 10;
float maxTurn = 10;
void OnCollisionEnter2D (Collision2D collision)
{
Quaternion randomRotation = Quaternion.Euler(0, 0, Random.Range(-maxTurn, maxTurn));
rb.velocity = randomRotation * (rb.velocity.normalized * minVelocity);
}
This code will set the velocity of the ball to its previous velocity, but with a magnitude of minVelocity. It will also rotate that vector a random amount of degrees to make it bounce in different directions.
I am trying to instantiate a prefab, a fireball, from a baddie, and at the time of instantiation pass the current player position to the fireball and use this to target the fireball at the player. The fireball translates/moves forward on its transform.forward vector. Thus the fireball should head from the baddie towards the player's position at the time the fireball was created.
What I am finding is that the direction is being set (via the transform.lookat() function on the fireball), but it is almost always the wrong direction. It is not 90 or 180 off. How much it is off by depends on where the player is in respect to the baddie. The pattern is symmetrical around the z axis.
Assuming the baddie is at (0,0,0):
when the player is at (0,0,10) the fireballs head directly towards the player
when the player is at (0,0,-10) the fireballs head away from the player (180 degrees. The exact opposite direction. The same direction as when the player was at (0,0,10))
when the player is at (10,0,0) the fireballs head 90 degrees away from the player (to the players right if facing the baddie)
when the player is at (-10,0,0) the fireballs head 90 degrees away from the player (to the players left if facing the baddie)
These values move smoothly as the player moves through these angles. It only ever hits the player in one direction.
I have tried the following (some of these were probably not required):
re-import all assets
create new project on a new machine to reproduce the issue.
I've tried setting the lookat variable to be:
player transform
the vector 3 world coordinate of the player (this is what is in the code below)
player.transform.position - baddie.transform.position
baddie.transform.position - player.transform.position
These all yield the same results.
Here is my code.
Code to Instantiate the fireball from the baddie.
public class Baddie : MonoBehaviour {
public GameObject fireballPrefab;
public GameObject playerGameObject;
public float countDownForFireball;
private float currentCountDownForFireball;
void Start () {
playerGameObject = GameObject.FindGameObjectWithTag("Player");
currentCountDownForFireball = 0;
}
void Update () {
if(currentCountDownForFireball <= 0)
{
GameObject newFireball = GameObject.Instantiate(fireballPrefab, transform.position, Quaternion.identity);
newFireball.GetComponent<Fireball>().SetTarget(playerGameObject.transform.position);
currentCountDownForFireball = countDownForFireball;
}
else
{
currentCountDownForFireball -= Time.deltaTime;
}
}
}
Code on the fireball
public class Fireball : MonoBehaviour {
private float moveSpeed;
private Vector3 target;
// Use this for initialization
void Start () {
moveSpeed = 15f;
}
// Update is called once per frame
void Update (){
transform.Translate(transform.forward * Time.deltaTime * moveSpeed);
}
public void SetTarget(Vector3 newTarget){
target = newTarget;
transform.LookAt(target);
}
}
The error is in the usage of Transform.Translate. Its secondary parameter is a Space argument that defaults to Space.Self. You want the space of your direction to match the space you're translating in so you want to pass in Space.World:
// transform.forward is the transform's forward vector in "world space"
transform.Translate(transform.forward * Time.deltaTime * moveSpeed, Space.World);
Alternatively, you can keep using the default Space.Self with Vector3.forward instead of transform.forward:
// Vector3.forward is (0,0,1). In "self space" this is "forward"
transform.Translate(Vector3.forward * Time.deltaTime * moveSpeed); // Space.Self
I'm making a basic 2D space shooter game in unity. I have the movements working fine and the camera follows the player. I've been scratching my head over how to give the camera a slight delay from the player moving to the camera moving to catch up to it without it teleporting. I was told to use a Vector3.Lerp and tried a few things from stackoverflow answers but none seemed to work with the way my code is set up. Any suggestions?
(myTarget is linked to the player)
public class cameraFollower : MonoBehaviour {
public Transform myTarget;
void Update () {
if(myTarget != null){
Vector3 targPos = myTarget.position;
targPos.z = transform.position.z;
transform.position = targPos;
}
}
}
If you linear interpolate (Lerp) you risk that Time.deltaTime * speed > 1 in which case the camera will start to extrapolate. That is, instead of following it will get in front if your target.
An alternative is to use pow in your linear interpolation.
float speed = 2.5f;
float smooth = 1.0f - Mathf.Pow(0.5f, Time.deltaTime * speed);
transform.position = Vector3.Lerp(transform.position, targetPos, smooth);
Mathf.Pow(0.5, time) means that after 1/speed second, half of the distance to the target point will be travelled.
The idea with Lerping camera movement is to gradually and smoothly have the camera make its way to the target position.
The further away the camera is, the bigger the distance it will travel per frame, but the closer the camera is, the distance per frame becomes smaller, making the camera ease into its target position.
As an example, try replacing your transform.position = targPos; line with:
float speed = 2.5f; // Set speed to whatever you'd like
transform.position = Vector3.Lerp(transform.position, targPos, Time.deltaTime * speed);