Enemy movement just on some portion of ground 2D Unity - c#

Can I make my enemy move just on some suspended blocks? I have a script but my enemy fall of them and doesn't stop when is not any block around . I am bound to put blocks higher just to stop his fall?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
private float latestDirectionChangeTime;
private readonly float directionChangeTime = 3f;
private float characterVelocity = 2f;
private Vector2 movementDirection;
private Vector2 movementPerSecond;
void Start()
{
latestDirectionChangeTime = 0f;
calcuateNewMovementVector();
}
void calcuateNewMovementVector()
{
//create a random direction vector with the magnitude of 1, later multiply it with the velocity of the enemy
movementDirection = new Vector2(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f)).normalized;
movementPerSecond = movementDirection * characterVelocity;
}
void Update()
{
//if the changeTime was reached, calculate a new movement vector
if (Time.time - latestDirectionChangeTime > directionChangeTime)
{
latestDirectionChangeTime = Time.time;
calcuateNewMovementVector();
}
//move enemy:
transform.position = new Vector2(transform.position.x + (movementPerSecond.x * Time.deltaTime),
transform.position.y + (movementPerSecond.y * Time.deltaTime));
}
}

Related

change direction into random direction on collision Unity2D

I'm new to unity and I'm trying to create a game where there's a ball that can move
in the direction by dragging and releasing on the screen and that change direction randomly when hitting a prefab, I already created that kind of movement but couldn't figure out how to make the ball change direction randomly when hitting the prefab.
Sorry if this isn't the right place to ask.
Here's my script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] private float power = 2;
[SerializeField] private Vector2 minPow, maxPow;
public Vector3 force;
private Vector3 startPoint, endPoint;
private Rigidbody2D rb;
private Camera cam;
private Aim aim;
void Start()
{
cam = Camera.main;
rb = GetComponent<Rigidbody2D>();
aim = GetComponent<Aim>();
}
void Update()
{
if(Input.GetMouseButtonDown(0))
{
startPoint = cam.ScreenToWorldPoint(Input.mousePosition);
startPoint.z = 15;
}
if(Input.GetMouseButton(0))
{
Vector3 currentPos = cam.ScreenToWorldPoint(Input.mousePosition);
startPoint.z = 15;
aim.RenderLine(startPoint, currentPos);
}
if(Input.GetMouseButtonUp(0))
{
endPoint = cam.ScreenToWorldPoint(Input.mousePosition);
endPoint.z = 15;
force = new Vector3(Mathf.Clamp(startPoint.x - endPoint.x, minPow.x, maxPow.x), Mathf.Clamp(startPoint.y - endPoint.y, minPow.y, maxPow.y));
rb.AddForce(force * power, ForceMode2D.Impulse);
aim.EndLine();
}
}
public void BoostUp(float pow)
{
rb.velocity *= pow;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Boost : MonoBehaviour
{
[SerializeField] float pow;
private void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Player")
{
Player player = other.GetComponent<Player>();
if(player != null)
{
player.BoostUp(pow);
Destroy(this.gameObject);
}
}
}
}
You can get a random angle in radians using Random.Range(0f, 2f * Mathf.PI) and then pass it to Mathf.Cos and Mathf.Sin functions to get a direction with that angle:
float angle = Random.Range( 0f, 2f * Mathf.PI );
Vector2 direction = new Vector2( Mathf.Cos( angle ), Mathf.Sin( angle ) );

My player rotation influnce my movement joystick how i fix this?

I crate a joystick and I calculate the direction the joystick make then with my direction I calculate my angle when I calculate my angle I duplicate my script so now one joystick for moving in script one and one joystick are for rotation in script 2, my problem is that when I rotate my player, let's say 90 degrees my move joystick moves the player to a different direction
The move joystick code have the angle calculate
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using Unity.Mathematics;
using UnityEditor;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
public class joystick : MonoBehaviour
{
public Transform player;
public float speed;
private bool touchStart = false;
private Vector2 pointA;
private Vector2 pointB;
public Transform circle;
public Transform outerCircle;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Debug.Log(Input.mousePosition.x);
if (Input.GetMouseButtonDown(0))
{
if (Input.mousePosition.x < Screen.width / 2)
{
pointA = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z));
circle.GetComponent<SpriteRenderer>().enabled = true;
outerCircle.GetComponent<SpriteRenderer>().enabled = true;
circle.transform.position = pointA;
outerCircle.transform.position = pointA;
}
}
if (Input.GetMouseButton(0))
{
if (Input.mousePosition.x < Screen.width / 2)
{
pointB = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z));
touchStart = true;
}
}
else
{
touchStart = false;
circle.GetComponent<SpriteRenderer>().enabled = false;
outerCircle.GetComponent<SpriteRenderer>().enabled = false;
}
}
private void FixedUpdate()
{
if (touchStart)
{
if (Input.mousePosition.x < Screen.width/2)
{
Vector2 offset = pointB - pointA;
Vector2 direction = Vector3.ClampMagnitude(offset, 1.0f);
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg - 90;
Quaternion angleAxis = Quaternion.AngleAxis(angle, Vector3.forward);
movePlayer(direction);
circle.transform.position = new Vector2(pointA.x + direction.x, pointA.y + direction.y);
}
}
}
void movePlayer(Vector2 direction)
{
player.Translate(direction + player.rotation) * speed * Time.deltaTime);
}
}

C#: y axis velocity increasing over time

So....i worked on some code that makes your rocket rotate when you press space
and added a force to the right and it seems like as you go more the velocity increases, why is that?
Sorry for my exprimation, I'm a beginner in unity and programming so..dodon't judge me
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerMovement: MonoBehaviour
{
private float gravity;
public float moveSpeed = 20f;
private Rigidbody2D rb;
private Vector2 startPos;
public Vector2 velocity;
public static PlayerMovement Instance
{
get;
set;
}
// Start is called before the first frame update
private void Start()
{
Instance = this;
startPos = transform.position;
rb = GetComponent < Rigidbody2D > ();
gravity = rb.gravityScale;
}
// Update is called once per frame
private void Update()
{
Vector2 vel = rb.velocity;
float ang = Mathf.Atan2(vel.y, x: 30) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(x: 0, y: 0, z: ang - 90));
rb.AddForce( - velocity * Time.deltaTime, ForceMode2D.Impulse);
rb.AddForce(Vector2.right * 500 * Time.deltaTime);
if (Input.GetKey(KeyCode.Space)) {
rb.AddForce(Vector2.up * 3000 * gravity * Time.deltaTime);
}
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Obstacle")
{
Die();
}
}
void Die()
{
SceneManager.LoadScene(0);
}
}
RigidBody.AddForce is the reason, whenever you using it, it add a force to your game object, and you do this on each frame.

Unity - Quaternion.Slerp instantly rotating

I am trying to have my object smoothly rotate on the Z axis from 0 to 180, back and forth on every button press.
The Quaternion.Slerp setup i'm using does not smoothly rotate to the target rotation, rather it instantly jumps to a number close to it. After many button presses that call the Quaternion.Slerp, it it finally halfs works in that it goes from 0 to 180, but still instantly and not smoothly.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
public bool movePlayer;
private float maxMoveSpeed;
public float waitToMove;
Rigidbody2D thisRigidbody;
//SCOOP variables
private GameObject scoop;
private GameObject scoopRotation;
Quaternion currentScoopRotation;
public Quaternion targetScoopRotation;
Quaternion lastScoopRotation;
public float scoopRotateTime;
// Use this for initialization
void Start ()
{
thisRigidbody = gameObject.GetComponent<Rigidbody2D> ();
maxMoveSpeed = moveSpeed;
//SCOOP finders
scoop = GameObject.FindGameObjectWithTag ("Scoop");
currentScoopRotation = scoop.transform.rotation;
}
// Update is called once per frame
void Update ()
{
if(movePlayer)
thisRigidbody.velocity = new Vector2 (moveSpeed, thisRigidbody.velocity.y);
//Rotates SCOOP using Quaternions + Spacebar
if (Input.GetKeyDown(KeyCode.Space)) {
lastScoopRotation = currentScoopRotation;
scoop.transform.transform.rotation = Quaternion.Lerp (currentScoopRotation, targetScoopRotation, scoopRotateTime * Time.time);
currentScoopRotation = targetScoopRotation;
targetScoopRotation = lastScoopRotation;
changeMoveDirection ();
}
}
void changeMoveDirection()
{
moveSpeed *= -1;
}
IEnumerator changeDirectionCO()
{
//thisRigidbody.velocity = new Vector2 (0f,0f);
//moveSpeed = 0;
yield return new WaitForSeconds (waitToMove);
moveSpeed *= -1;
}
}

Move Camera in UnityScript 2d in C#

I have just started programming Unity 2d, and I have faced one large problem: How do I move the camera? The script is attached to the object "player". I want it to move with the player. Thanks!
/*
I
*/
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float speed = 10; //Float for speed
public string hAxis = "Horizontal";
void Start ()
{
//empty
}
void FixedUpdate ()
{
if (Input.GetAxis (hAxis) < 0) //Left
{
Vector3 newScale = transform.localScale;
newScale.y = 1.0f;
newScale.x = 1.0f;
transform.localScale = newScale;
}
else if (Input.GetAxis (hAxis) > 0) //Right
{
Vector3 newScale =transform.localScale;
newScale.x = 1.0f;
transform.localScale = newScale;
}
//Position transformation
transform.position = transform.position + transform.right * Input.GetAxis(axisName) * speed * Time.deltaTime;
}
}
Without any scripts, you could just drag the Camera GameObject to be a child of the player and the camera would start following the player position.
For a script, try this, set player as the target.
using UnityEngine;
using System.Collections;
public class SmoothCamera2D : MonoBehaviour {
public float dampTime = 0.15f;
private Vector3 velocity = Vector3.zero;
public Transform target;
// Update is called once per frame
void Update ()
{
if (target)
{
Vector3 point = camera.WorldToViewportPoint(target.position);
Vector3 delta = target.position - camera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, point.z)); //(new Vector3(0.5, 0.5, point.z));
Vector3 destination = transform.position + delta;
transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, dampTime);
}
}
}

Categories