Updated position Unity3d - unity3d

I have a bullet that has to hit a constantly moving enemy.
So, in BulletScript, I have declared a Transform
public Transform enemy; //and assigned enemy object to it that is continuously moving and changing its position
Now, when I try to use enemy.position in bullet script so as to hit it, enemy.positiongives the position at which the enemy strted and not the position at which it was when bulletprefab was shot.
How can I get the updated position of enemy object every time bulletprefab is instantiated.
This is how I am changing the enemy's position:
void Update () {
float amttomove = currentSpeed * Time.deltaTime;
transform.Translate (Vector3.left * amttomove);
if (transform.position.x < 0f)
setposandspeed();
}
void setposandspeed()
{
x = 11.5f;
z = 0.0f;
currentSpeed = Random.Range (MinSpeed, MaxSpeed);
y = Random.Range (0f, 2.5f);
transform.position = new Vector3(x, y, z);
}
This is where tried to use enemy's position in bulletscript:
float target_Distance = Vector3.Distance(Projectile.position, Target.transform.position );
It is called inside Start() of bulletscript
This is where I instantiated the bullet in Player class:
Inside Updated method:
if (Input.GetKeyDown ("space")) {
Vector3 position = new Vector3 (transform.position.x, transform.position.y + collider.bounds.size.y / 2);
Instantiate (bulletprefab, position, Quaternion.identity);
}

enemy.position in bullet script so as to hit it, enemy.positiongives
the position at which the enemy strted and not the position at which
it was when bulletprefab was shot.
No, enemy.position will return the current position of the enemy, suitable if you want your projectile follow the enemy.
If you are instantiating dynamically your projectiles (BullerScript) and want to shoot them toward the position the enemy is during the shoot frame, record it just after bullet is instantiated for example:
class BulletScript : MonoBehavior
{
public Vector3 targetPos;
void Update()
{
//move toward targetPos
}
}
BulletScript bullet = GameObject.Instantiate(bulletPrefab,shootPosition) as BulletScript;
bullet.targetPos = enemyPosition;

Related

How can I make a 2D gun shoot towards the Direction of the mouse rather than the Position of the mouse?

Currently, my gun is able to instantiate new bullets that work fine (they have velocity and shoot towards the mouse's position). However, if the mouse is close to the player, I noticed the velocity is drastically lessened because it is targeting the mouse's position instead of the general direction.
Is there a way to get the angle from the player to the mouse, as well as apply velocity to the bullet, without it going exactly to the mouse's position?
public GameObject bullet;
public GameObject player;
// All the following is within an update function
//Gets the mouse position, and assigns direction from gun to mouse
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = mousePosition - transform.position;
float angle = Vector2.SignedAngle(Vector2.right, direction);
Vector2 PlayerDimensions = player.transform.lossyScale;
Vector2 PlayerLocation = player.transform.position;
//If the Gun weapon type is selected
if (weaponType == 2)
{
// Is used to flip the player sprite based on if the gun is facing left or right
if (PlayerLocation.x > mousePosition.x)
{
PlayerDimensions.x = -1;
player.transform.localScale = new Vector2(PlayerDimensions.x, PlayerDimensions.y);
}
else if (PlayerLocation.x < mousePosition.x)
{
PlayerDimensions.x = 1;
player.transform.localScale = new Vector2(PlayerDimensions.x, PlayerDimensions.y);
}
// Aims the gun based on if player is facing left or right
if (player.transform.lossyScale.x > 0)
{
transform.eulerAngles = new Vector3(0, 0, angle);
}
else if (player.transform.lossyScale.x < 0)
{
transform.eulerAngles = new Vector3(0, 0, 180 + angle);
}
}
if (Input.GetMouseButtonDown(0) && weaponType == 2)
{
Debug.Log("Shoot");
Vector3 myPos = new Vector3(transform.position.x, transform.position.y);
GameObject Bullet = Instantiate(bullet, myPos, Quaternion.identity);
Physics2D.IgnoreCollision(Bullet.GetComponent<BoxCollider2D>(), player.GetComponent<BoxCollider2D>(), GameObject.Find("blue_bullet_medium(Clone)"));
Bullet.GetComponent<Rigidbody2D>().velocity = new Vector2(direction.x, direction.y);
}
You can use normalized vector and speed instead of just direction to get constant bullet speed. In code it will be like this:
Vector2 direction = mousePosition - transform.position;
direction.Normalize();
Vector2 bulletVelocity = direction * _speed; // assume _speed can be tuned
The normalized vector will always have length 1, so the speed will not depend on the distance from the player to the cursor position

Unity 2D instantiate prefabs order

I'm instantiating enemy prefabs in waves, but when I do, the sprites are not consistent on the Z axis. Sometimes the second enemy is on top of the first one, and sometimes behind.
I want the new instance always behind the other.
Keep the instance position and instantiate the gameobject behind.
GameObject myGo1 = GameObject.Instantiate(prefabRef, Vector3.Zero,
Quaternion.Identity);
float distance = 1.0f;
Vector3 myGo2Pos = myGo1.position - myGo1.transform.forward * distance;
GameObject myGo2 = GameObject.Instantiate(prefabRef, myGo2Pos, Quaternion.Identity);
For the 1st GO instatiation, where Vector3.Zero you can choose the position of your choice. For whatever pos and rot you instantiate myGo1 with, the code Vector3 myGo2Pos = myGo1.position - myGo1.forward * distance; should instantiate the 2nd one distance meters behind.
Not debugged code, just for your inspiration.
Probably you might need the 2nd GO to look to the first one, in that case you can do:
GameObject myGo2 = GameObject.Instantiate(prefabRef, myGo2Pos, myGo1.transform.rotation);
Alright i figured it out. had to add a sprite renderer component like so:
SpriteRenderer spriteRenderer;
and where i instantiate:
void FollowPath()
{
if (!isAttacking)
{
if (waypointIndex < waypoints.Count)
{
**spriteRenderer = GetComponent<SpriteRenderer>();
spriteRenderer.sortingOrder++;**
Vector3 targetPosition = waypoints[waypointIndex].position;
float delta = waveconfig.GetMoveSpeed() * Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, targetPosition, delta);
if (transform.position == targetPosition)
{
waypointIndex++;
}
}
}
}

How can I move an object bullet towards a target?

I want to shoot a bullet prefab towards a target. I want it to just go towards the target current location. If the target changes position the bullets should still go to the old target position, instead of the current position the target is at.
Vector2 pos;
pos.x = tracker.transform.position.x;
pos.y = tracker.transform.position.y;
transform.position = Vector2.MoveTowards(transform.position, pos, bulletSpeed * Time.deltaTime);
The above code just makes the bullet prefab track the object even though the object moves. If an object is at 0,0 then the bullet should go towards it but if the player changes its position to 1,1 the bullet should still go to 0,0
Simply cache the previous position that the object was at and MoveTowards that instead of the player as that will go to the current position. Instead of continually updating the pos.x and pos.y, set them initially when the bullet is fired and not again.
private Vector2 targetPos;
private bool bulletInited = false;
private float bulletSpeed;
public void InitBulletTarget(Vector2 target)
{
bulletInited = true;
targetPos = target;
}
private void Update()
{
if(bulletInited)
{
transform.position = Vector2.MoveTowards(transform.position, targetPos, bulletSpeed * Time.deltaTime);
}
}
When you Instantiate your bullet prefab, you will want to call the InitBulletPosition and send in the proper position which would be the tracker.transform.position.
An example would be
private void SpawnBullet()
{
// spawn the two bullets
YourBulletScript bullet1 = Instantiate(bullet, firePoint.position, firePoint.rotation).GetComponent<YourBulletScript>();
YourBulletScript bullet2 = Instantiate(bullet, firePoint2.position, firePoint2.rotation).GetComponent<YourBulletScript>();
// set their target position to move towards
bullet1.InitBulletTarget(tracker.transform.position);
bullet2.InitBulletTarget(tracker.transform.position);
}

Raycast 2D ricochet in Unity?

I'm new to Raycasting so I might be going about this in a bad way, but I would to send a raycast outward to direction a gameobject is facing, bounce off the first object it hits and go a short distance before disappearing.
As far as I can tell there is no built in function for reflecting raycasts in Unity, so I have been trying to generate a another raycast where the first one hits but my luck hasn't been going well. Here's what I have so far:
public Gameobject firePoint; // I have an object attached to my main object that I use as a point of origin
void DrawLazer()
{
Vector2 origin = new Vector2(firePoint.transform.position.x, firePoint.transform.position.y);
Vector2 direction = transform.TransformDirection(Vector2.up);
RaycastHit2D hit = Physics2D.Raycast(origin, direction, 10f);
Debug.DrawLine(origin, direction *10000, Color.black);
if (hit)
{
Debug.Log("Hit: " + hit.collider.name);
var whatWeHit = new Vector2(hit.transform.position.x, hit.transform.position.y);
var offset = whatWeHit + hit.point;
offset.y = 0;
RaycastHit2D hit2 = Physics2D.Raycast(offset, Vector3.Reflect(direction, hit.normal) * -10000);
if (hit2)
{
Debug.DrawLine(offset, -Vector3.Reflect(direction, hit.normal) * -10000);
}
}
}
I call DrawLaxer(); in update.
This current script is sort of able to generate a 2nd raycast, however as you can see, the first raycast still does not stop when it hits something, and more importantly while this solution works well when it hits a flat object on a horizontal plane. But if it hits on object on a vertical or diagonal plane it applys several calculations to the wrong axis:
Any help would be greatly appreciated.
Here is a complete example monobehavior that uses Vector2.Reflect and SphereCast.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ReflectionExample : MonoBehaviour
{
public GameObject firePoint;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
DrawPredictionDisplay();
}
private void DrawPredictionDisplay()
{
Vector2 origin = firePoint.transform.position; //unity has a built in type converter that converts vector3 to vector2 by dropping the z component
Vector2 direction = firePoint.transform.up;
float radius = 1.0f;
RaycastHit2D distanceCheck = Physics2D.Raycast(origin, direction);
RaycastHit2D hit = Physics2D.CircleCast(origin, radius, direction);
Debug.DrawLine(origin, direction * 10000, UnityEngine.Color.black);
DrawCircle(origin, 1.0f, UnityEngine.Color.black);
if (hit)
{
origin = hit.point + (hit.normal * radius);
direction = Vector2.Reflect(direction, hit.normal);
hit = Physics2D.CircleCast(origin, radius, direction);
Debug.DrawLine(origin, direction * 10000, UnityEngine.Color.blue);
DrawCircle(origin, 1.0f, UnityEngine.Color.blue);
}
}
private void DrawCircle(Vector2 center, float radius, UnityEngine.Color color)
{
Vector2 prevPoint = new Vector2(Mathf.Sin(0f), Mathf.Cos(0f));
for (float t = 0.1f; t < 2 * Mathf.PI; t = t + 0.1f)
{
var nextPoint = new Vector2(Mathf.Sin(t), Mathf.Cos(t));
Debug.DrawLine(center + prevPoint, center + nextPoint, color);
prevPoint = nextPoint;
}
}
}

Make the character face the direction he is moving?

I know I should have posted this question on Unity's questions page but I actually did and haven't received an answer for 3 days.
So I'm trying to make the character face the direction it is moving but I can't make it work. I'm working on a 3d game with a diablo-style camera but without depending on the mouse, and I'm using the script from 'Survival Shooter' as a reference.
Here's the movement script:
public float speed = 6f; // The speed that the player will move at.
public float rotateSpeed = 2f;
public Camera playerCam;
Vector3 movement; // The vector to store the direction of the player's movement.
Animator anim; // Reference to the animator component.
Rigidbody playerRigidbody; // Reference to the player's rigidbody.
int floorMask; // A layer mask so that a ray can be cast just at gameobjects on the floor layer.
float camRayLength = 100f; // The length of the ray from the camera into the scene.
Vector3 rotationY;
void Awake ()
{
// Create a layer mask for the floor layer.
floorMask = LayerMask.GetMask ("Floor");
// Set up references.
anim = GetComponent <Animator> ();
playerRigidbody = GetComponent <Rigidbody> ();
}
void FixedUpdate ()
{
// Store the input axes.
float h = Input.GetAxisRaw ("Horizontal");
float v = Input.GetAxisRaw ("Vertical");
// Move the player around the scene.
Move (h, v);
// Turn the player to face the mouse cursor.
Turning (h, v);
}
void Move (float h, float v)
{
// Move the player to it's current position plus the movement.
Vector3 targetDirection = new Vector3(h, 0f, v);
targetDirection = Camera.main.transform.TransformDirection(targetDirection);
targetDirection = targetDirection.normalized * speed * Time.deltaTime;
targetDirection.y = 0.0f;
playerRigidbody.MovePosition (transform.position + targetDirection);
}
void Turning(float y, float x)
{
if (y != 0) {
rotationY.Set (0f, y, 0f);
//rotationY = rotationY.normalized * (5 * rotateSpeed);
Quaternion deltaRotation = Quaternion.Euler (rotationY);
playerRigidbody.MoveRotation (deltaRotation);
}
}
However when I move the character it always faces the bottom-left side of the screen. How can I fix that?