How can I make the android to mvoe between the waypoints randomly? - c#

Since the android should fly or move in the air too I guess I should also use physics too ? Not sure.
I added some spheres as waypoints and I want the android to move between them randomly including random range of movement and rotation speed. For example 1-10 range randomly speed for both movement and rotation.
Now what it does when I'm running the game the NAVI (1) is just moving in rounds none stop on small area not sure why, But it's not moving smooth between the spheres.
The idea is to make the NAVI droid to act like it's out of order.
This is screenshot of the NAVI (1) and it's inspector:
This screenshot is of the Waypoints attached to it Waypoints script:
This is the Waypoints script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Waypoints : MonoBehaviour
{
public Transform objectToMove;
public float moveSpeed = 3.0f;
public float rotationSpeed = 3.0f;
public GameObject[] waypoints;
public int currentWP;
private void Awake()
{
}
private void Start()
{
currentWP = 0;
}
private void Update()
{
if (waypoints.Length == 0) return;
var lookPos = waypoints[currentWP].transform.position - objectToMove.position;
lookPos.y = 0;
var rotation = Quaternion.LookRotation(lookPos);
objectToMove.rotation = Quaternion.Slerp(objectToMove.rotation, rotation, Time.deltaTime * rotationSpeed);
objectToMove.position += objectToMove.forward * moveSpeed * Time.deltaTime;
}
}

You are never changing currentWP. That means at every frame, you're rotating toward the same nav point and moving the droid back towards it.
You have to change the currentWP only when the droid reaches it. Use OnTrigger between the target nav point and the droid.

You can do it something like this .
//for example you've got 5 waypoints
currentWaypoint = Random.Range(1, 5);
Hope it helps

Related

How can I lock the rotation of a player in Unity?

I'm currently making a 2D game as a beginner and I made a spinning platform. But when it's rotating the player's rotation (z-axis) also changes because it's a child of the platform. I need this when I use moving platforms. Now I want to lock the z-axis of the rotation of the player. I already tried it in 3 different ways, but none of them seems to be working. Does anybody know how to do this?
These are the three ways I tried:
// 1
PlayerTrans.transform.Rotate(
PlayerTrans.transform.rotation.x,
PlayerTrans.transform.rotation.y,
0);
// 2
PlayerTrans.transform.Rotate(
PlayerTrans.transform.rotation.x,
PlayerTrans.transform.rotation.y,
0,
Space.Self);
// 3
PlayerTrans.transform.localRotation = Quaternion.Euler(new Vector3(
PlayerTrans.transform.localEulerAngles.x,
PlayerTrans.transform.localEulerAngles.y,
0f));
and this is, what my code looks like for staying on the moving platforms. I used raycasting for this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Raycasting : MonoBehaviour
{
// Start is called before the first frame update
Transform PlayerTrans;
public float RayCastRange = 3;
void Start()
{
PlayerTrans = transform.parent;
}
// Update is called once per frame
void Update()
{
RaycastHit2D PlattformCheck = Physics2D.Raycast(transform.position, -Vector2.up, RayCastRange);
if (PlattformCheck.collider != null)
{
if (PlattformCheck.collider.gameObject.tag == "Platform")
{
PlayerTrans.transform.SetParent(PlattformCheck.collider.gameObject.transform);
}
else
{
PlayerTrans.transform.SetParent(null);
}
}
else
{
PlayerTrans.transform.SetParent(null);
}
}
}
There are 2 ways that might help you:
Just freeze the rotation from the inspector:
you can use some LookAt function (there is one for 3D but you can look and find ones for 2D) and just look at the camera.
(if you cant find it let me know and I will add it)
You should raycast directly down and then apply velocities to both objects (un-child the player from the platforms). You could do something like this for the player:
public LayerMask mask; //set ‘mask’ to the mask of the
//platform in the Unity Editor.
public Vector3 velocity;
void Update()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, -Vector3.up, out hit, 0.1f, mask))
//0.1f is the distance to the platform to be able to be moved by the platform.
{
velocity = hit.collider.gameObject.GetComponent<Platform>().velocity;
}
float h = Input.GetAxis(“Horizontal”);
//this one is for CharacterController:
cc.Move(velocity);
//this one is for rigidbody:
rb.velocity = velocity;
velocity = 0;
}
It takes the velocity from the ‘Platform’ script and moves the player based on it. Now we should add the platform script. Call it ‘Platform’.
public Vector3 velocity;
public Vector3 a; //a and b are the two points you want the platform to go between.
public Vector3 b;
public float period = 2f; //the amount of seconds per cycle.
float cycles;
void Update()
{
cycles = Time.time / period;
float amplitude = Mathf.Sin(Mathf.PI * 2f * cycles);
Vector3 location = Vector3.Lerp(a, b, amplitude);
velocity = transform.position - location;
transform.position = velocity;
}
This script interpolates between the point a and b, then it finds the velocity and applies it. The player takes this velocity and it moves the player. Comment if you found an error.

Unity C# code to make my AI move not working as intended

I am in the process of creating a 3D single-player FPS and am currently working on the movement of the enemies in the game. As this is my first game and doesn't know C# that much I followed a tutorial to do this:
https://www.youtube.com/watch?v=_Z1t7MNk0c4
the tutorial was for 2d but said that it would wor for 3d as well
here is the script that I have
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movment_shoot : MonoBehaviour {
public float speed;
public float stoppingDistance;
public float retreatDistance;
private Transform player;
void Start() {
player = GameObject.FindGameObjectWithTag("Player").transform;
}
void Update() {
if (Vector2.Distance(transform.position, player.position) > stoppingDistance) {
transform.position = Vector2.MoveTowards(transform.position, player.position, speed *
Time.deltaTime);
} else if (Vector2.Distance(transform.position, player.position) < stoppingDistance &&
Vector2.Distance(transform.position, player.position) > retreatDistance) {
transform.position = this.transform.position;
} else if (Vector2.Distance(transform.position, player.position) < retreatDistance){
transform.position = Vector2.MoveTowards(transform.position, player.position, -speed *
Time.deltaTime);
}
}
}`
I have not added the shooting part yet when I run the game the enemy I have applied the script to teleports to a location just outside the terrain whilst the game is still playing if you move the enemy along if you try and move it along the x or z axes it will only move along x then go back to the original position if you move it along the y it will let you but then move back to its original position please help with anyways I can make this work correctly.
Pay attention with vectors in unity: lower dimensionality vectors operations "cut out" excess dimensions.
Your problem is that the Z is completely left out of the equation 😉.
You just need to use the methods of the Vector3 class rather than Vector2.

Mouse axes are based on position, not movement

Basically, when I have my cursor in the center of the screen, the camera doesn't rotate. Pretty standard. However, If I move my cursor to the left or right, It will start rotating. Still makes sense. However, When I stop moving the cursor, the rotation continues. I'm using an empty object and making the camera face in the same direction as that empty object. The problem is, the object continues to rotate. If I move the cursor back to the center of the screen, it stops rotating again. Something similar happens when I assign axes in the project settings to the right stick on an Xbox 1 controller. If I move the stick right, the camera begins to rotate, however, if I return the stick to the deadzone, it continues to rotate. If I then move the stick left, it will slow down the rotation, and eventually begin rotating the other direction. It doesn't happen with the vertical stick axis, though.
Here's my code with the mouse for the player and empty object rotation:
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public Transform PlayerT;
public Transform camT;
public Transform CamR;
public CharacterController controller;
public float speed;
public float CamRSpeed;
private float gravity;
private float HorizontalR;
private float VerticalR;
private Vector3 moveDirection;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
HorizontalR = Input.GetAxis("Mouse X") * CamRSpeed * Time.deltaTime;
VerticalR = Input.GetAxis("Mouse Y") * CamRSpeed * Time.deltaTime;
CamR.Rotate(VerticalR, HorizontalR, 0f);
PlayerT.forward = CamR.forward;
PlayerT.eulerAngles = new Vector3(0f, PlayerT.eulerAngles.y, 0f);
moveDirection = (PlayerT.forward * Input.GetAxis("Vertical") * speed) + (PlayerT.right * Input.GetAxis("Horizontal") * speed);
controller.Move(moveDirection * Time.deltaTime);
}
}
//and for the camera (this is a separate script, I'm just not entirely sure how this site's formatting works):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraScript : MonoBehaviour
{
public Transform cam;
public Transform player;
public Transform CamR;
private Vector3 offset;
// Start is called before the first frame update
void Start()
{
offset = CamR.position - cam.position;
}
// Update is called once per frame
void Update()
{
cam.eulerAngles = new Vector3(CamR.eulerAngles.x, CamR.eulerAngles.y, 0f);
cam.position = CamR.position - (CamR.rotation * offset);
}
}```
Well, as it turns out, it was simply because the object I was trying to rotate was a child of the player. I'm not entirely sure why it didn't work, but it does now.

Object kept falling as opposed to shooting trajectory (Unity)

everyone! I am new to Unity and try to create a 2D arcade game by allowing my character to jump up at a trajectory motion to reach something then fall down. I use gravity scale equal to 1 and move_speed 1000 and rest_speed 500 but as soon as I hit space, the character just fell down instead of going up.
Also, walk.IsWalk is an int from Walking class(as soon as I hit right arrow, set IsWalk to 2 for example). My expected result would be as soon as we hold both space and right arrow key, the character should move upwards follow a curved motion. I dont know what is going on here, can anyone kindly point me to a direction? Thanks!
My code as follows:
using UnityEngine;
using System.Collections;
public class Jumping : MonoBehaviour
{
Rigidbody2D rb2D;
Animator anim;
Walking walk = new Walking();
public float move_speed;
public float rest_speed;
void Start()
{
rb2D = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
void FixedUpdate()
{
//float xmove = Input.GetAxis("Horizontal");
//float ymove = Input.GetAxis("Vertical");
//var curr = new Vector2(xmove, ymove);
if (Input.GetKey("space"))
{
anim.SetTrigger("JumpButtonPres");
rb2D.gravityScale = 1;
if (walk.isWalk == 2)
{
rb2D.AddForce(rb2D.position * move_speed);
}
else if (walk.isWalk == 1)
{
//rb2D.velocity += (Vector2.up * (-rb2D.velocity.x));
rb2D.AddForce(-rb2D.position * move_speed);
}
else
{
rb2D.AddForce(rb2D.position * rest_speed);
}
}
}
}
partial code for rigidbody2D.AddForce
It seems your problem is that whenever you are adding force to your rigidbody, you are multiplying it by the position where it's located, so by this i'm guessing your character is placed at a negative y component coordenate, and this is why rb2D.position * rest_speed will result on your playing falling. Change it for vector2.up * rest_speed and you should be fine.
Hope I was able to help.
Noé

Unity2D - Companion

When reading this, keep in mind I'm new to both programming and Unity, so I might be missing some terms or tools Unity offer. Please elaborate your answers in an ELI5 manner. Thanks in advance!
I am currently working on some game-physics for a small personal project. Currently I've created a platform, a character and what should be, a following companion.
However, since I'm still not on a level, where I can create perfect code on own hand, I found an "enemy" script and tried to modify it a bit.
It Works to an extend, but it needs some tweaks which I hope I can help aquire with you guys.
This is how it looks now (the orange square is the companion)
It follows the player, and I can tweak the speed to fit as a companion, and not a player. However, as the Picture presents, the companion runs for the center of the player. What I want to create is a companion which follows the player, but still keeps a small gap from the player.
My first thoughts was to create some kind of permanent offset, but I fail to figure out how to do this without messing up the follow function.
I hope you can help me, it will be much appreciated!
Here's the code for reference.
Code attached to Player:
using UnityEngine;
using System.Collections;
public class PlayerCompanion : MonoBehaviour
{
//In the editor, add your wayPoint gameobject to the script.
public GameObject wayPoint;
//This is how often your waypoint's position will update to the player's position
private float timer = 0.5f;
void Update ()
{
if (timer > 0) {
timer -= Time.deltaTime;
}
if (timer <= 0) {
//The position of the waypoint will update to the player's position
UpdatePosition ();
timer = 0.5f;
}
}
void UpdatePosition ()
{
//The wayPoint's position will now be the player's current position.
wayPoint.transform.position = transform.position;
}
}
Code attached to companion:
using UnityEngine;
using System.Collections;
public class FollowerOffset : MonoBehaviour {
//You may consider adding a rigid body to the zombie for accurate physics simulation
private GameObject wayPoint;
private Vector3 wayPointPos;
//This will be the zombie's speed. Adjust as necessary.
private float speed = 10.0f;
void Start ()
{
//At the start of the game, the zombies will find the gameobject called wayPoint.
wayPoint = GameObject.Find("wayPoint");
}
void Update ()
{
wayPointPos = new Vector3(wayPoint.transform.position.x, transform.position.y, wayPoint.transform.position.z);
//Here, the zombie's will follow the waypoint.
transform.position = Vector3.MoveTowards(transform.position, wayPointPos, speed * Time.deltaTime);
}
}
bump, I guess ? :)
You can use smooth follow script. I have created a sample class for you. This class has features to follow any given gameobject with some delay and offset. You will have to tweak some values according to your need.
using UnityEngine;
using System.Collections;
public class PlayerCompanion : MonoBehaviour
{
[SerializeField]
private GameObject wayPoint;
[SerializeField]
public Vector3 offset;
public Vector3 targetPos;//Edit: I forgot to declare this on firt time
public float interpVelocity;
public float cameraLerpTime = .1f;
public float followStrength = 15f;
// Use this for initialization
void Start ()
{
//At the start of the game, the zombies will find the gameobject called wayPoint.
wayPoint = GameObject.Find("wayPoint");
offset = new Vector3 (5,0,0);//input amount of offset you need
}
void FixedUpdate () {
if (wayPoint) {
Vector3 posNoZ = transform.position;
Vector3 targetDirection = (wayPoint.transform.position - posNoZ);
interpVelocity = targetDirection.magnitude * followStrength;
targetPos = transform.position + (targetDirection.normalized * interpVelocity * Time.deltaTime);
transform.position = Vector3.Lerp (transform.position, targetPos + offset, cameraLerpTime);
}
}
}
Attach this class to your player companion, play with different values.
To preserve object orientation your companion schould not be anyways child of your main character.
Your wayPoint doesn't needs to be a GameObject but a Transform instead and your code will looks like better.
If your game is a 2D platform your and your companion needs to be backwards your player it probabli applys to just one axis (X?) so you can decrement your waiPoint in a more directly way by calculating it on your UpdatePosition function like this:
wayPoint.position = transform.position * (Vector3.left * distance);
where your "distance" could be a public float to easily setup.
so on your companion script Update just do:
transform.position = Vector3.MoveTowards(transform.position, wayPoint.position, speed * Time.deltaTime);
I can't test it right now so you could have problems with Vector3 multiply operations, just comment and I'll try to fix as possible ;)

Categories