Enemies movement is not smooth - c#

When my enemies move, they move from one position to the next without moving in between the points. I want the enemies to move between two positions smoothly, and I do not understand why the enemies do not do so with the following code.
public class UltPatrol : MonoBehaviour
{
public float speed;
public Transform Enemypos;
private float waitTime;
public float StartwaitTime;
public float MinX;
public float MaxX;
public float MinY;
public float MaxY;
private void Start()
{
Enemypos = GetComponentInParent<Transform>();
waitTime = StartwaitTime;
Enemypos.localPosition = new Vector2(Random.Range(MinX, MaxX), Random.Range(MinY, MaxY));
}
private void Update()
{
transform.localPosition = Vector2.MoveTowards(transform.localPosition, Enemypos.localPosition, speed * Time.deltaTime);
if (Vector2.Distance(transform.localPosition, Enemypos.localPosition) <0.2f)
{
if (waitTime <= 0)
{
Enemypos.localPosition = new Vector2(Random.Range(MinX, MaxX), Random.Range(MinY, MaxY));
waitTime = StartwaitTime;
}
else
{
waitTime -= Time.deltaTime;
}
}
}
}

Are you trying to get your game to look like this
All I did was remove the line
Enemypos = GetComponentInParent<Transform>();
And then in the editor, I un-parented the two objects, and assigned the value of Enemypos in the inspector.

Related

How I can move player left or right with infinite runner game here. using character controller

public class PlayerMove : MonoBehaviour
{
public float speed;
private float yVelocity;
public CharacterController player;
public float jumpHeight =10.0f;
public float gravity = 1.0f;
//public float gravityScale = 1;
private void Start()
{
player = GetComponent<CharacterController>();
}
void Update()
{
Vector3 direction= new Vector3(0, 0, 1);
Vector3 velocity= direction * speed;
if (player.isGrounded == true)
{
if (Input.GetKeyDown(KeyCode.Space))
{
yVelocity = jumpHeight;
}
}
else
{
yVelocity -= gravity;
}
velocity.y = yVelocity;
player.Move(velocity * Time.deltaTime);
}
}
I tried Rigidbody & much more script but my player doesn't jump if my player jump then my doesn't move left or right sometimes my player stocked in ground.. tell me the right way of script where I can use
For the left/right movements you can try this simple code :
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
public float speed;
private float yVelocity;
public CharacterController player;
public float jumpForce = 10.0f;
public float moveForce = 5.0f;
public float gravity = 1.0f;
private void Start()
{
player = GetComponent<CharacterController>();
}
void Update()
{
Vector3 direction = new Vector3(0, 0, 1);
Vector3 velocity = direction * speed;
// Add left/right movement
if (Input.GetKey(KeyCode.LeftArrow))
{
velocity += Vector3.left * moveForce;
}
else if (Input.GetKey(KeyCode.RightArrow))
{
velocity += Vector3.right * moveForce;
}
if (player.isGrounded)
{
if (Input.GetKeyDown(KeyCode.Space))
{
yVelocity = jumpForce;
}
}
else
{
yVelocity -= gravity;
}
velocity.y = yVelocity;
player.Move(velocity * Time.deltaTime);
}
}
You can also look at this post Moving player in Subway Surf like game using left/right swipe

player collision does not work with objects

I'm making an endless runner game and i have a question about my player colliding with so,e obstacles, I used Raycast but when i try to debug this collision doesn't occur.
Here my player Code.
public class Player : MonoBehaviour
{
private CharacterController controller;
public float speed;
public float jumpHeight;
private float jumpVelocity;
public float gravity;
public float rayRadius;
public LayerMask layer;
public float horizontalSpeed;
private bool isMovingLeft;
private bool isMovingRight;
private bool isDead;
// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
Vector3 direction = Vector3.forward * speed;
if(controller.isGrounded)
{
if(Input.GetKeyDown(KeyCode.Space))
{
jumpVelocity = jumpHeight;
}
if(Input.GetKeyDown(KeyCode.RightArrow)&& transform.position.x < 3.58f && !isMovingRight)
{
isMovingRight = true;
StartCoroutine(RightMove());
}
if(Input.GetKeyDown(KeyCode.LeftArrow)&& transform.position.x > -3.58f && !isMovingLeft)
{
isMovingLeft = true;
StartCoroutine(LeftMove());
}
}
else
{
jumpVelocity -= gravity;
}
OnCollision();
direction.y = jumpVelocity;
controller.Move(direction * Time.deltaTime);
}
IEnumerator LeftMove()
{
for(float i = 0; i < 10; i += 0.1f)
{
controller.Move(Vector3.left * Time.deltaTime * horizontalSpeed);
yield return null;
}
isMovingLeft = false;
}
IEnumerator RightMove()
{
for (float i = 0; i < 10; i += 0.1f)
{
controller.Move(Vector3.right * Time.deltaTime * horizontalSpeed);
yield return null;
}
isMovingRight = false;
}
void OnCollision()
//The player will collide with obstacles that have a specific type of layer and dead.
{
RaycastHit hit;
if(Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, rayRadius, layer) && !isDead)
{
Debug.Log("GameOver!");
speed = 0;
jumpHeight = 0;
isDead = true;
}
}
}
Instead of using raycast inside OnCollision function. You can do this with very much by following these steps:
Add a tag to your obstacles let say its "Obstacle"
Add collider to them
Check when you collide with someone that if it is obstacle or not if yes then you can call your dead function.
void OnCollisionEnter(Collision collision)
{
if(collision.transform.CompareTag("Obstacle")){
Debug.Log("GameOver!");
speed = 0;
jumpHeight = 0;
isDead = true;
}
}
In this way you can detect collision with super ease instead of using raycast.

how can I make the game object disappear?

when I was watching on YouTube, tutorials about endless runner on part 2, the game object wouldn't disappear when it hits the player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Obstacle : MonoBehaviour
{
public int damage = 1;
public float speed;
private void Update()
{
transform.Translate(Vector2.left * speed * Time.deltaTime);
}
void onTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("rocket"))
{
//rocket takes damage 1
other.GetComponent<rocket>().health -= damage;
Debug.Log(other.GetComponent<rocket>().health);
Destroy(gameObject);
}
}
}
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class rocket : MonoBehaviour
{
private Vector2 targetPos;
public float Yincrement;
public float speed;
public float maxHeight;
public float minHeight;
public int health = 3;
void Update()
{
if (health <= 0)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.UpArrow) && transform.position.y < maxHeight)
{
targetPos = new Vector2(transform.position.x, transform.position.y + Yincrement);
}
else if (Input.GetKeyDown(KeyCode.DownArrow) && transform.position.y > minHeight)
{
targetPos = new Vector2(transform.position.x, transform.position.y - Yincrement);
}
}
}
from this one https://www.youtube.com/watch?v=FVCW5189evI and I'm confused why it didn't work, can someone tell me what is wrong?
if you want to destroy use this, Correct Method to get the game object when collide is: other.gameObject
void onTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("rocket"))
{
//rocket takes damage 1
other.gameObject.GetComponent<rocket>().health -= damage;
Debug.Log(other.gameObject.GetComponent<rocket>().health);
Destory(other.gameObject);
}
}
public class megaStar : MonoBehaviour{
private Rigidbody2D rb;
private Animator _ani;
public bool canAttack = true;
[SerializeField] private Attack _attackObject;
private AudioSource _as;
public checkpoint lastCheckpoint;
public bool isDead = false;
private float _timer = 1.0f;
public float attackTimer = 2.0f;
public GameObject projectile;
public float projectileSpeed = 18.0f;
public Transform projectileAttackPoint;
public float timeDelayForNextShoot = 0.1f;
private float CONST_timeDelayForNextShoot;
// Start is called before the first frame update
void Start(){
CONST_timeDelayForNextShoot = timeDelayForNextShoot;
rb = GetComponent<Rigidbody2D>();
_as = GetComponent<AudioSource>();
_ani = GetComponent<Animator>();
_timer = attackTimer;
}
void Update(){
if (Input.GetKey(KeyCode.W))
{
rb.velocity = new Vector2(0f, 10f);
}
else if (Input.GetKey(KeyCode.S))
{
rb.velocity = new Vector2(0f, -10f);
}
else
{
rb.velocity = new Vector2(0f, 0f);
}
timeDelayForNextShoot -= Time.deltaTime;
if (Input.GetKeyDown(KeyCode.K) && timeDelayForNextShoot <= 0f){
_ani.SetBool("projectileAttack", true);
GameObject go = Instantiate(projectile, projectileAttackPoint.position, projectileAttackPoint.rotation) as GameObject;
go.GetComponent<Rigidbody2D>().velocity = new Vector2(-projectileSpeed, 0.0f);
Destroy(go, 2.0f);
timeDelayForNextShoot = CONST_timeDelayForNextShoot;
canAttack = false;
// new WaitForSeconds(1);
return;
}
}
void FixedUpdate()
{
if (!isDead)
{
Update();
}
else{
rb.velocity = Vector2.zero;
RigidbodyConstraints2D newRB2D = RigidbodyConstraints2D.FreezePositionY;
rb.constraints = newRB2D;
}
}
private void OnCollisionEnter2D(Collision2D collision){
if (collision.gameObject.CompareTag("Enemy"))
{
GetComponent<HitPoints>().TakeDamage(1);
}
}
}
Use SetActive instead of Destroy Function.
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("rocket"))
{
//rocket takes damage 1
other.gameObject.GetComponent<rocket>().health -= damage;
Debug.Log(other.gameObject.GetComponent<rocket>().health);
gameObject.SetActive(false);// it'll Hide GameObject instead of Destroying
// gameObject.SetActive(true);// to show again
}
}

Unity how to detect if a specific Game Object is near you

I'm creating a test game because I'm getting ready to create my first game but I want to make sure I get all the simple mechanics down that my first game will require. One of the mechanics that will be included in the game is picking up items if they are a certain distance to you. Sometimes there might be multiple of the same object in the game, I figured the code would work for all coins however that is just not the case. The Debug.Log() only works on one specific coin, how do I make it so it will fire no matter what coin I'm near?
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour {
//Player Variables
public float moveSpeed;
public float jumpHeight;
public float raycastDistanceGround;
public Text moneyText;
private bool isGrounded;
private Rigidbody _rgb;
private GameObject player;
private GameObject[] coin;
private float distanceToCollectCoin;
private float distanceToCoin;
void Start () {
moveSpeed = 7f;
jumpHeight = 9f;
raycastDistanceGround = 0.5f;
isGrounded = true;
_rgb = GetComponent<Rigidbody>();
player = GameObject.FindGameObjectWithTag("Player");
coin = GameObject.FindGameObjectsWithTag("Coin");
distanceToCollectCoin = 2f;
Cursor.lockState = CursorLockMode.Locked;
}
void FixedUpdate () {
IsGrounding();
Move();
Jump();
SetMoneyText();
NearCoin();
}
//Player Moving Mechanics
void Move() {
var moveHorizontal = Input.GetAxis("Horizontal") * moveSpeed * Time.fixedDeltaTime;
var moveVertical = Input.GetAxis("Vertical") * moveSpeed * Time.fixedDeltaTime;
transform.Translate(moveHorizontal, 0f, moveVertical);
if (Input.GetKeyDown(KeyCode.Escape)) {
Cursor.lockState = CursorLockMode.None;
}
}
//Player Jump Mechanics
void Jump() {
var jump = new Vector3(0f, _rgb.position.y, 0f);
if (Input.GetKey(KeyCode.Space) && isGrounded == true) {
for (float i = 0; i <= jumpHeight; i++) {
jump.y += i;
_rgb.AddForce(jump);
}
}
}
void IsGrounding() {
if (Physics.Raycast(transform.position, Vector3.down, raycastDistanceGround)) {
isGrounded = true;
} else {
isGrounded = false;
}
}
void SetMoneyText() {
moneyText.text = ("Money: " + EconomyController.Money);
}
void NearCoin() {
for (int i = 0; i < coin.Length; i++) {
distanceToCoin = Vector3.Distance(coin[i].transform.position, player.transform.position);
}
if (distanceToCoin < distanceToCollectCoin) {
Debug.Log("Near Coin");
}
}
}
Looks like you just bracketed some stuff wrong. You need to move your if-statement into the for-loop. Right now it's only checking the distance for the last coin in the array.
void NearCoin()
{
for (int i = 0; i < coin.Length; i++)
{
distanceToCoin = Vector3.Distance(coin[i].transform.position, player.transform.position);
if (distanceToCoin < distanceToCollectCoin)
Debug.Log("Near Coin");
}
}

I have error in collision on bullet shoot

I have a problem on the bullet collision the enemy
I am using the OnCollisionEnter() method in the Bullet Script
Bullet Script :
public class BulletScript : MonoBehaviour
{
public float TimeForDestory = 10f;
public float Speed = 0.5f;
// Use this for initialization
void Start () {
}
public void OnCollisionEnter(Collision col)
{
Debug.Log("Collision");
if (col.gameObject.tag == "Enemy")
{
Debug.Log("Collision");
}
}
// Update is called once per frame
void Update () {
transform.Translate(0, -Speed, 0);
if (TimeForDestory < 0f)
{
Destroy(gameObject);
}else
{
TimeForDestory -= 0.1f;
}
}
}
The Bullet Not Collision Anything
the bullet is out of the objects because I am using Method Instantiate() in the Player Script
Player Script :
public class Player : MonoBehaviour
{
//Player
//Move
public float defualtSpdPlayer = 1f;
public float plsSpd = 0.1f;
public float maxPlayer = 2f;
private float speed = 0;
//Bullet
public Transform bulletSpawn;
public GameObject bullet;
public Texture ImgBackground;
public Texture ImgWhiteGround;
public Texture ImgReloading;
public float bulletDamge = 1f;
public float bulletSpeed = 0.1f;
public float ReloadTime = 0.5f;
public float ReloadFillAmontX = 2f;
private float reload = 0;
private float reloadFillAmont = 0;
private bool readyToShoot = true;
private string status = "Ready";
//GUI
[HideInInspector]
public bool guiShow = true;
void Start () {
MoveStart();
BulletStart();
}
private void MoveStart()
{
speed = defualtSpdPlayer;
}
private void BulletStart()
{
if(ReloadTime > 1)
{
Debug.LogError("The Reload Time Is Bigger 1");
}
}
void OnGUI()
{
//Verables
float cvReloadingWidth = 150;
float cvReloadingHeight = 150;
float cvReloadngY = Screen.height - cvReloadingHeight;
float cvReloadngX = Screen.width / 2 - 70;
//Rects
Rect cvReloadingImages = new Rect(cvReloadngX, cvReloadngY, cvReloadingWidth, cvReloadingHeight);
Rect cvReloadinglalReloadTime = new Rect(cvReloadngX + 65, cvReloadngY + 75, cvReloadingWidth, cvReloadingHeight);
Rect cvReloadinglalStatus = new Rect(cvReloadngX + 40, cvReloadngY + 50, cvReloadingWidth, cvReloadingHeight);
//Texts
//Values
//Texture
GUI.DrawTexture(cvReloadingImages, ImgBackground);
GUI.DrawTexture(cvReloadingImages, ImgWhiteGround);
//GUI.DrawTexture(cvReloadingImages, ImgReloading);
if (reloadFillAmont <= 0)
{
GUI.skin.label.normal.textColor = Color.green;
GUI.skin.label.fontSize = 25;
GUI.skin.label.fontStyle = FontStyle.Bold;
GUI.Label(cvReloadinglalStatus, status);
GUI.skin.label.fontSize = 15;
GUI.skin.label.fontStyle = FontStyle.Bold;
GUI.Label(cvReloadinglalReloadTime, ReloadTime.ToString());
}
else
{
GUI.skin.label.normal.textColor = Color.red;
GUI.Label(cvReloadinglalStatus, status);
GUI.Label(cvReloadinglalReloadTime, reloadFillAmont.ToString());
}
//GUI
}
void Update () {
Move();
Shoot();
}
private void Move()
{
//Move
if (transform.rotation.y < 180)
{
plsSpeed();
transform.Translate(Input.GetAxis("BW") * speed * Time.deltaTime, 0, Input.GetAxis("FW") * speed * Time.deltaTime);
}
if (transform.rotation.y >= 180)
{
plsSpeed();
transform.Translate(-Input.GetAxis("BW") * speed * Time.deltaTime, 0, -Input.GetAxis("FW") * speed * Time.deltaTime);
}
}
private void plsSpeed()
{
if (speed > maxPlayer)
{
speed = defualtSpdPlayer;
}
else
speed += plsSpd;
}
//Gun Shoot
private void Shoot()
{
if (readyToShoot)
{
if (Input.GetMouseButton(0))
{
Instantiate(bullet, bulletSpawn.position, bulletSpawn.rotation);
readyToShoot = false;
reload = ReloadTime;
status = "Reloading";
}
status = "Ready";
}
else
{
reloadFillAmont = reload * ReloadFillAmontX;
if (reload < 0)
{
readyToShoot = true;
}else
{
reload -= Time.deltaTime;
status = "Reloading";
}
}
}
}
What's the problem in the collision ?
You are using transform.Translate(0, -Speed, 0); to move the bullet, when you use this the bullet is going to move regardless any obstacle/force outside of it. To fix this add a Rigidbody to the bullet and change that line to GetComponent<Rigidbody>().MovePosition(transform.position - Vector3.up * Speed);
Because its a bullet it might be a fast moving object so put the Collision Detection to Continuous on the Rigidbody.

Categories