Raycast from the player position to the mouse position within range - c#

I want to make a raycast from the player position to the mouse position but it should only have a certain range.
I have tried the following:
using UnityEngine;
public class Raycasting : MonoBehaviour
{
public GameManager gm;
Vector3 worldPosition;
public Transform player;
void FixedUpdate()
{
//Debug.Log(Camera.main.ScreenToWorldPoint(Input.mousePosition));
Debug.DrawLine(player.transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition), Color.green);
RaycastHit2D hit = Physics2D.Raycast(player.transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition), 10f);
if(hit.collider.tag == "Enemy")
{
Debug.Log (hit.collider.gameObject);
gm.Attack();
if (GameManager.enemyhealth <= 0)
{
Debug.Log("Enemy Died!");
Destroy(hit.transform.gameObject);
}
}
}
}
in Debug.DrawLine() it works exactly as I want it to — without the range —, but the raycast dosen't detect the enemies around it.

There is a trick to getting the ray end point to solve your problem. Just make sure your camera is orthographic. Also, by determining the enemy layer, detection problems are eliminated.
public GameObject player;
public LayerMask enemyLayer;
void Update()
{
var point = Camera.main.ScreenPointToRay(Input.mousePosition).GetPoint(1);
point.z = player.transform.position.z;
Debug.DrawLine(player.transform.position, point);
var enemy = Physics2D.Linecast(player.transform.position, point, enemyLayer.value);
if (enemy)
{
// do something...
}
}
Also, if you want to control the distance, please leave a comment.
Limited Distance to pointer
This algorithm limits the distance. For example, if you enter 5 for distance, the maximum magnitude will be 5, and if the mouse approaches below 5, it will set the mouse point to the maximum.
public GameObject player;
public LayerMask enemyLayer;
public float distance = 4.5f;
void FixedUpdate()
{
var point = Camera.main.ScreenToWorldPoint(Input.mousePosition);
point.z = player.transform.position.z;
var clamp = Vector3.ClampMagnitude(point - player.transform.position, distance);
Debug.DrawLine(player.transform.position, player.transform.position+clamp);
var enemy = Physics2D.Linecast(player.transform.position, player.transform.position+clamp, enemyLayer.value);
if (enemy)
{
Debug.Log("Detected..");
}
}
Fixed Distance along pointer direction
This algorithm takes the mouse to the player and then adds the size. Mouse location does not affect size and distance is fixed.
public GameObject player;
public LayerMask enemyLayer;
public float distance = 4.5f;
void FixedUpdate()
{
var point = Camera.main.ScreenPointToRay(Input.mousePosition).GetPoint(1);
point.z = player.transform.position.z;
var direction = (point - player.transform.position).normalized;
Debug.DrawRay(player.transform.position, direction*distance);
var enemy = Physics2D.Raycast(player.transform.position, direction, distance, enemyLayer.value);
if (enemy)
{
Debug.Log("Detected..");
}
}

Related

Unity 2D RaycastHit2D not detecting collision continuously?

I am quite new to unity and recently i began a little project with raycasters but now I have encontered a problem:
I am tring to shoot a Raycast from the centre of the screen to my mouse with a distance:
This is what it looks like
The problem is that I want the distance of the Raycast to change dependion on wheter there is collision occuring but the collision detection is not continuous and the Raycast flickers between the collsion point and its normal distance:
Here it take the normal distance value
Here the distance value is the point of collsion
This is the code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreateRay : MonoBehaviour
{
[SerializeField] float distance = 10f;
Ray2D ray;
Vector2 mouseposition;
RaycastHit2D raycastHit2D;
void Update()
{
mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
private void FixedUpdate()
{
CheckColliders();
}
void CheckColliders()
{
int layermask = 1 << 8;
layermask = ~layermask;
RaycastHit2D raycastHit2D = Physics2D.Raycast(Vector2.zero, mouseposition, distance, layermask);
if (raycastHit2D.collider != null)
{
distance = raycastHit2D.distance;
new WaitForEndOfFrame();
}
else if (raycastHit2D.collider == null)
{
distance = 15;
}
Debug.DrawRay(Vector2.zero, mouseposition.normalized * distance, Color.yellow);
}
}
The thing that changes the values is the else if statement but without it the distance of the Raycast would change one and not return to its original distance.

Unity 2D - how to have enemy chasing a target avoid an object using raycast

I have an enemy which is chasing a target. This works great, however there is a square object in the center of the map. If the target is on one side of the square and the enemy on the other, the enemy will get stuck on the object since it's moving in the direction of the target.
I have a raycast which does detect the object if it's within a certain range. The piece I am missing is how do I now make the enemy go around the object?
//check where the target is and set a straight line
Rigidbody2D targetRb = target.GetComponent(typeof(Rigidbody2D)) as Rigidbody2D;
Vector2 targetPos = targetRb.position;
// rb is current game object rigid body
Vector2 toVec = targetPos - rb.position;
// ...
// ...
// At this point I have a RaycastHit2D object which is the hit on the object.
// Can I update toVec, or rb (current rigid body) to make the enemy avoid the object?
// ...
// ...
// Later I move the enemy towards the target with the following
rb.velocity = new Vector2(toVec.normalized.x * moveSpeed, toVec.normalized.y * moveSpeed);
I think using A* or a bezier curve between two points would be a better approach, but my solution is to draw a ray between two points and if there is an obstacle between them, take a random point between the first point and the second one and draw two rays between the three new points, so if you have multiple obstacles it still can find a way (use the method for your path finding, the Gizmos method is for demonstration purposes):
[SerializeField] private Transform start;
[SerializeField] private Transform end;
[SerializeField] private List<Vector3> position;
[SerializeField] private LayerMask layerMask;
[SerializeField] private bool calculate;
private void OnValidate()
{
if (!calculate) return;
position = new List<Vector3>();
calculate = false;
position.Add(start.position);
Calculate(start.position, end.position);
position.Add(end.position);
}
private void Calculate(Vector3 p0, Vector3 p1)
{
var direction = (p1 - p0).normalized;
// hits obstacle
if (Physics.Raycast(p0, direction, 1000, layerMask))
{
position.Remove(p1);
var middle = (p0 + p1) / 2;
middle.y += Random.Range(2, 5);
position.Add(middle);
Calculate(p0, middle);
Calculate(middle, p1);
}
}
private void OnDrawGizmos()
{
Gizmos.DrawLine(start.position, end.position);
for (int i = 0; i < position.Count - 1; i++)
{
Gizmos.DrawLine(position[i + 1], position[i]);
}
}
and this is how it corrects the way:
nevertheless, it can lead to infinity:

Unity3D: How to move an object in relation to another object?

I have a physics enabled sphere in my scene and a character that i can move around using WASD. now what i want is that as soon as player hits the ball it should not be physics enabled anymore and move along with player as like the player is holding it in the hands.
What i have tried so far:
i was able to do it but not at all perfect how i want it to be. i tried OnCollisionEnter to detect the collision, i made the sphere a child of the player, i used isKinematic = true as soon as collision is detected and i used Vector3.MoveTowards for the object to follow the position as the player.
I have attached two reference videos below
Reference Clip(The style i am aiming for):https://www.youtube.com/watch?v=fi-GB0RwLr0
MyVersion(This is what i am able to do):https://www.youtube.com/watch?v=JtV11KHY4pU
overall, if you watch the clips you can see how my version is very rigid, stucky, buggy, not so light weight feeling at all. Cut me a slack as well if i did anything way wrong, i started unity like just in the previous month.
This is my Player script through which i am controlling it all
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Player : MonoBehaviour
{
public float MoveSpeed;
[SerializeField]private Rigidbody playerRig;
[SerializeField] private Rigidbody ballRig;
[SerializeField] private GameObject Ball;
[SerializeField] private GameObject heldObj;
private bool isTouching = false;
private Vector3 offset = new Vector3(0, 1, 3);
private Vector3 force;
public float jump;
private bool isGrounded = true;
private void Start()
{
Ball = GameObject.FindGameObjectWithTag("Ball");
ballRig.GetComponent<Rigidbody>();
playerRig.GetComponent<Rigidbody>();
}
void Update()
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
playerRig.velocity = new Vector3(x*MoveSpeed, playerRig.velocity.y,z*MoveSpeed);
Vector3 vel = playerRig.velocity;
vel.y = 0;
if (vel.x != 0 || vel.z != 0)
{
transform.forward = vel;
}
if(transform.position.y < -10)
{
GameOver();
}
ReleaseTheBall();
if (isTouching == true)
{
ballRig.transform.position = Vector3.MoveTowards(ballRig.transform.position, playerRig.transform.position, 5f);
}
}
void Jump()
{
force = new Vector3(0, jump, 0);
if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true)
{
isGrounded = false;
playerRig.AddForce(force, ForceMode.Impulse);
}
}
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == "Ball" && heldObj == null)
{
ballRig.isKinematic = true;
// ballRig.constraints = RigidbodyConstraints.FreezeRotation;
ballRig.transform.parent = playerRig.transform;
isTouching = true;
Debug.Log(" BALL PICKED UP AND MOVING ");
heldObj = Ball;
}
}
public void ReleaseTheBall()
{
if (Input.GetKeyDown(KeyCode.Space) && heldObj != null)
{
isTouching = false;
heldObj = null;
ballRig.transform.parent = null;
//ballRig.constraints = RigidbodyConstraints.None;
ballRig.isKinematic = false;
//Vector3 forceDirection = new Vector3(playerRig.transform.position.x, 0, playerRig.transform.position.z);
Vector3 rotationDirection = new Vector3(playerRig.transform.rotation.x, playerRig.transform.rotation.y, playerRig.transform.rotation.z);
ballRig.AddForce(new Vector3(transform.position.x,0,transform.position.z) * 5, ForceMode.Impulse);
ballRig.AddTorque(rotationDirection * 1);
Debug.Log("BALL RELEASED");
}
}
public void GameOver()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
i know there could be some very inefficient lines of code here, feel free to call out those lines as well.
So, basically what i want is that i want my player to pick up the ball as soon as it hits it and the ball should move exactly like player as if he is holding the ball in his hands and when i hit the spacebar i want the ball to be released into the direction i am looking(this part is also very tricky for me), what i am trying to do is i want to do exactly like in the refrence clip. Thanks a lot in advance.
one more thing, when i stop pressing any key to move(WASD), my player transform keeps changing values up and down and it slightly starts moving. i mean when i dont press any key, it still kinda moves.
First of all, you have indeed quite a lot of lines that aren't useful in here and that could be optimized.
Anyway, I hope this will do what you want it to do:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
[RequireComponent(typeof(Rigidbody))]
public class Player : MonoBehaviour {
[Header("Movement Setup")]
[Tooltip("Translation speed in m/s")]
[SerializeField] float _TranslationSpeed;
[Tooltip("Rotation speed in °/s")]
[SerializeField] float _RotationSpeed;
[Tooltip("Interpolation speed [0;1]")]
[SerializeField] float _InterpolationSpeed;
[Tooltip("Strength for jumps")]
[SerializeField] float _JumpingStrength;
[Tooltip("Strength for shoots")]
[SerializeField] float _ShootingStrength;
[Header("Other Settings")]
[Tooltip("Where the helded item will be placed")]
[SerializeField] Transform _ContactPoint;
[Tooltip("Which layers should be considered as ground")]
[SerializeField] LayerMask _GroundLayer;
// The player's rigid body
Rigidbody _Rigidbody;
// Is the player on the ground
bool _IsGrounded;
// Rigidbody of what's the player is helding. Null if the player isn't holding anything
Rigidbody _HeldedItemRigidbody;
// Getter to _IsGrounded, return true if the player is grounded
public bool IsGrounded { get { return _IsGrounded; } }
private void Start() {
_Rigidbody = GetComponent<Rigidbody>(); // The player's rigidbody could be serialized
}
void FixedUpdate() {
float horizontalInput, verticalInput;
// Getting axis
horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");
// Moving toward the x
Vector3 moveVect = transform.forward * _TranslationSpeed * Time.fixedDeltaTime * verticalInput;
_Rigidbody.MovePosition(_Rigidbody.position + moveVect);
// Rotating the player based on the horizontal input
float rotAngle = horizontalInput * _RotationSpeed * Time.fixedDeltaTime;
Quaternion qRot = Quaternion.AngleAxis(rotAngle, transform.up);
Quaternion qRotUpRight = Quaternion.FromToRotation(transform.up, Vector3.up);
Quaternion qOrientationUpRightTarget = qRotUpRight * _Rigidbody.rotation;
Quaternion qNewUpRightOrientation = Quaternion.Slerp(_Rigidbody.rotation, qOrientationUpRightTarget, Time.fixedDeltaTime * _InterpolationSpeed); // We're using a slerp for a smooth movement
_Rigidbody.MoveRotation(qRot * qNewUpRightOrientation);
// This prevents the player from falling/keep moving if there is no input
if (_IsGrounded) _Rigidbody.velocity = Vector3.zero;
_Rigidbody.angularVelocity = Vector3.zero;
if (transform.position.y < -10) GameOver();
if (Input.GetKey(KeyCode.Mouse0) && _HeldedItemRigidbody != null) ShootTheBall();
if (!_IsGrounded) return; // What's below this won't be executed while jumping
if (Input.GetKey(KeyCode.Space)) Jump();
}
void Jump() {
_IsGrounded = false;
_Rigidbody.AddForce(_JumpingStrength * transform.up, ForceMode.Impulse);
}
private void OnCollisionEnter(Collision collision) {
// Checking if the player encountered a ground object
if ((_GroundLayer & (1 << collision.gameObject.layer)) > 0) _IsGrounded = true;
if (collision.gameObject.tag == "Ball") { // this can be improved as tags are error prone
// Setting the item position to contact point
collision.gameObject.transform.position = _ContactPoint.position;
// Getting the rigidbody
_HeldedItemRigidbody = collision.gameObject.GetComponent<Rigidbody>();
// Setting the parent
_HeldedItemRigidbody.transform.parent = transform;
// Setting the body to be kinematic
_HeldedItemRigidbody.isKinematic = true;
// Stopping any movement or rotation
_HeldedItemRigidbody.velocity = Vector3.zero;
_HeldedItemRigidbody.angularVelocity = Vector3.zero;
}
}
public void ShootTheBall() {
// Reverting what's done in OnCollisionEnter
_HeldedItemRigidbody.transform.parent = null;
_HeldedItemRigidbody.isKinematic = false;
// Adding force for the shoot
_HeldedItemRigidbody.AddForce(transform.forward * _ShootingStrength, ForceMode.Impulse);
// Resetting helding item to null
_HeldedItemRigidbody = null;
}
public void GameOver() {
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
You have to add a layer, and set the ground to this new layer.
Set up the variable as you like, don't hesitate to mess up with it a little bit to find what suits you (and don't forget to set up the player's mass (in rigidbody) as well!!)
Exemple of setup for the player script
Last things, you have to add an empty game object to your player which will be where the ball will be placed. I know it's a little bit dirty but place it a bit far from the player (more than the ball's radius) or it will bug. We could do something programatically to fix the ball at a spot and adapt this spot to the ball's radius.
This is an example of player
As you can see, I have the empty "player" gameobject which has the rigidbody, the collider and the player script.
The GFX item which is just the capsule.
If you don't know about this: the player game object is actually on the floor (at the player's feet) so it's better for movements. If you do this, don't forget to adjust the player's capsule collider to fit the GFX.
I also have the contact point.
Forget about the nose stuff, it's just a way to see where the player is facing when you just have a capsule.
If you have any question, feel free to ask.

FPS Projectile firing from the wrong place

I'm trying to make a basic FPS game in Unity and I'm having an issue where the projectiles I shoot won't instantiate in the right place. From what I can tell, the projectile instantiates in roughly the same position relative to the player regardless of where I look (that position being a little to the left of the starting angle of the player).
Here's a 20 second video demonstration of what I'm talking about.
https://youtu.be/WLVuqUtMqd0
Even when I'm facing the exact opposite direction of where the projectile usually instantiates it still spawns in the same place, which means the projectile ends up spawning behind the player and hitting the player.
I tried using Debug.DrawRay() to see if maybe the firepoint itself is wrong (which would be shown by the ray starting somewhere other than the gun barrel). However it seems like the starting point of the ray is correct every time.
I'm not sure if this is related to the issue above, but I have noticed that the ray direction is wrong if I'm looking a little below the horizon. It seems like the projectile's direction is correct regardless though.
Ray directions when looking slightly above the horizon vs. lower
Here's my code for intantiating/shooting the projectile. I think the most relevant parts are probably shootProjectile() and instantiateProjectile(). This script is attached to the player character.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooting : MonoBehaviour
{
public Camera cam;
public GameObject projectile;
public Transform firePoint;//firePoint is set to the end of the barrel.
public float projectileSpeed = 40;
//private var ray;
private Vector3 destination;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//var ray = cam.ViewportPointToRay(new Vector3(0.5f,0.5f,0));
//Debug.DrawRay(ray.origin, ray.direction);
if(Input.GetButtonDown("Fire1")) {
//player is shooting
ShootProjectile();
}
}
void ShootProjectile() {
Ray ray1 = cam.ScreenPointToRay(Input.mousePosition);
//Debug.Log(ray.direction);
RaycastHit hit;
if(Physics.Raycast(ray1, out hit))//checking whether the player is going to hit something
{
destination = hit.point;
}
else {
destination = ray1.GetPoint(1000);
}
Debug.DrawRay(firePoint.position, destination, Color.white, 10f);
InstantiateProjectile(firePoint);
}
void InstantiateProjectile(Transform firePoint) {
var projectileObj = Instantiate (projectile, firePoint.position, Quaternion.identity) as GameObject;//projectile is instantiated
projectileObj.GetComponent<Rigidbody>().velocity = (destination - firePoint.position).normalized * projectileSpeed;//projectile is set in motion
}
}
Here's the location of firePoint.
firePoint (i.e. where the projectile should instantiate)
I would appreciate any help on this, as I've been trying to fix it (on and off) for several days, and really have no idea what the problem is.
Edit: Here's my player movement script(s) as well. The first one is PlayerController.cs, and it converts the player's inputs into the appropriate movement vectors and camera rotation. It then calls methods from PlayerMotor.cs, which actually performs the movements.
PlayerController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(PlayerMotor))]
public class PlayerController : MonoBehaviour
{
[SerializeField]
public float speed = 10f;
[SerializeField]
private float lookSens = 3f;
private PlayerMotor motor;
void Start() {
motor = GetComponent<PlayerMotor>();
//Debug.Log("PlayerControllerStart");
Cursor.lockState = CursorLockMode.Locked;
}
void Update() {
//Debug.Log("PlayerControllerUpdate");
//calculate movement velocity as 3D vector.
float xMov = Input.GetAxisRaw("Horizontal");
float zMov = Input.GetAxisRaw("Vertical");
Vector3 movHorizontal = transform.right * xMov;
Vector3 movVertical = transform.forward * zMov;
Vector3 velocity = (movHorizontal + movVertical).normalized * speed;
motor.move(velocity);
//speed*=(float)1.15;
//rotation
float yRot = Input.GetAxisRaw("Mouse X");
Vector3 rotation = new Vector3 (0f, yRot, 0f) * lookSens;
motor.rotate(rotation);
float xRot = Input.GetAxisRaw("Mouse Y");
Vector3 cameraRotation = new Vector3 (xRot, 0f, 0f) * lookSens;
motor.rotateCamera(cameraRotation);
if (Input.GetKeyDown(KeyCode.Space) == true && motor.isGrounded()) {
motor.canJump=true;
}
if (Input.GetKey(KeyCode.W) == true) {
motor.accel=true;
}
else{
motor.accel=false;
}
}
}
PlayerMotor:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMotor : MonoBehaviour
{
[SerializeField]
private Camera cam;
private Vector3 velocity = Vector3.zero;
private Vector3 rotation = Vector3.zero;
private Vector3 cameraRotation = Vector3.zero;
private Vector3 jumpVector = new Vector3 (0f, 5f, 0f);
private PlayerController pc;
private Rigidbody rb;
public bool canJump;
public bool accel;
public float acceleration;
int jumpCount;
void Start() {
rb = GetComponent<Rigidbody>();
pc = GetComponent<PlayerController>();
canJump=false;
jumpCount=0;
accel=false;
//acceleration = 1.0;
//distToGround = collider.bounds.extents.y;
//Debug.Log("PlayerMotorStart");
}
//sets velocity to a given movement vector.
public void move(Vector3 _velocity) {
velocity = _velocity;
}
public void rotate(Vector3 _rotation) {
rotation = _rotation;
}
public void rotateCamera(Vector3 _cameraRotation) {
cameraRotation = _cameraRotation;
}
public bool isGrounded() {
return Physics.Raycast(transform.position, -Vector3.up, (float)2.5);
}
public void jump() {
rb.AddForce(transform.up * 250f);
//Debug.Log("Jump"+jumpCount);
jumpCount++;
canJump=false;
}
void FixedUpdate() {
performMovement();
performRotation();
if (canJump) {
jump();
}
//Debug.Log("PlayerMotorUpdate");
if(accel&&pc.speed<20f&&isGrounded())
{
//Debug.Log("W Pressed");
pc.speed*=(float)1.005;
}
else if(!accel) {
pc.speed=7f;
}
}
void performMovement() {
if(velocity != Vector3.zero) {
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
//Debug.Log("Movement");
}
}
void performRotation() {
rb.MoveRotation(rb.rotation * Quaternion.Euler(rotation));
if(cam != null) {
cam.transform.Rotate(-cameraRotation);
}
}
}
Here are some pictures of my projectile prefab as well.
To solve one first confusion: The method Debug.DrawRay takes as paramters
a start position
a ray direction(!)
You are passing in another position which is not what you want.
This might only work "accidentally" as long as you stand on 0,0,0 so maybe it wasn't that notable but the debt ray definitely points into a wrong direction.
Rather do e.g.
Debug.DrawRay(firePoint.position, destination - firePoint.position, Color.white, 10f);
Or instead rather use Debug.DrawLine which rather actually takes
start position
end position
Then you don't need to calculate the direction first
Debug.DrawLine(firePoint.position, destination, Color.white, 10f);
Then I suspect the following is happening: The spawned projectileObj actually is placed correctly but it is the visuals inside that projectile prefab that have a local offset against the parent prefab root.
Since you always spawn the projectile in world rotation Quaternion.identity that offset stays the same no matter where you look.
I guess a simple fix would already be to also apply the same rotation like
var projectileObj = Instantiate (projectile, firePoint.position, firePoint.rotation);

Why is my airplane moving only partway and not all the way?

So I've spent 2 days looking over this script, and I still don't see what I did wrong. I want to make a simple AI plane that will fly from one point to another. After arriving on Waypoint 1, it should fly towards Waypoint 2. I'll include my script below:
using UnityEngine;
using System.Collections
public class AICustomScript : MonoBehaviour
{
//first waypoint
public Transform Waypoint;
//second waypoint
public Transform Waypoint2;
void Start()
{
rb = GetComponent<Rigidbody>();
//make plane point in direction of first waypoint
transform.LookAt(Waypoint);
}
//allow me to select amount of force in editor
public float AddForceAmount;
//allow me to select plane in editor
public Rigidbody rb;
/void FixedUpdate()
{
//make plane move
rb.AddForce(transform.forward * AddForceAmount);
}
//PART OF CODE TO DETECT ARRIVAL ON WAYPOINT
void OnTriggerEnter(Collider other)
{
if (other.gameObject)
{
//destroys waypoint
Destroy(other.gameObject);
//makes plane look at 2nd waypoint (Waypoint2)
transform.LookAt(Waypoint2);
}
}
}
//SO WHAT'S WRONG?
I've included my logical thinking in the comments. However, when the plane arrives at Waypoint 1, it turns toward Waypoint 2, but only partially. So while it is flying towards the 2nd waypoint, it never "hits" it. Why?
Screenshots:
You might want to use spherical interpolation to make the airplane face the waypoint while changing its position. instead of adding forward force.
using UnityEngine;
using System.Collections;
public class AICustomScript : MonoBehaviour
{
public Transform[] Waypoints;
public float minimumTouchDistance = 2.0f; // minimum distance between the airplane and the waypoint
public float airplaneSpeed = 10.0f;
private Transform currentWaypoint; // keep track of current waypoint
private int currentIndex; // current position in the waypoint array
void Start()
{
currentWaypoint = Waypoints[0]; // set initial waypoint
currentIndex = 0; // set initial index
}
void Update()
{
faceAndMove();
if (Vector3.Distance(currentWaypoint.transform.position, transform.position) < minimumTouchDistance)
{
currentIndex++;
if (currentIndex > Waypoints.Length - 1)
{
currentIndex = 0;
}
currentWaypoint = Waypoints[currentIndex];
}
}
void faceAndMove()
{
Vector3 deltaPosition = currentWaypoint.transform.position - transform.position;
Vector3 calcVector = deltaPosition.normalized * airplaneSpeed * Time.deltaTime;
this.transform.position += calcVector;
this.transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(deltaPosition), 4 * Time.deltaTime);
}
}

Categories

Resources