Player Object spins continuously when moving joystick - c#

I have created a twin stick movement system for mobile. I have a character moving under the influence of one joystick correctly. The other joystick, the design I want is:
When the shoot JS is moved, look in that direction.
When the shoot JS is released, shoot in the last aimed direction.
What's happening is, the character shoots continuously when the game starts and if I move the ShootJS, the character spins in circles. I'm completely flummoxed as to why this is happening.
Here is my code. Thanks in advance to anybody for any help you provide.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.AI;
using Ludiq;
using Bolt;
public class PlayerJSControlSc : MonoBehaviour
{
public GameObject player;
public NavMeshAgent nav;
public Text stateText;
public float moveSpeed;
public Animator animator;
public FloatingJoystick moveJS;
public FloatingJoystick shootJS;
public float rotationSpeed = 10;
public int ammo;
public int mag;
public Transform shotSpawn;
public GameObject bullet;
public float reloadTime;
public Text ammoCount;
[HideInInspector]
int currentMag;
// Start is called before the first frame update
void Start()
{
stateText.text = "";
nav = player.GetComponent<NavMeshAgent>();
animator = player.GetComponent<Animator>();
moveJS = GameObject.Find("Floating JS_Move").GetComponent<FloatingJoystick>();
shootJS = GameObject.Find("Floating JS_Shoot").GetComponent<FloatingJoystick>();
}
// Update is called once per frame
void Update()
{
movePlayer();
playerShoot();
ammoCount.text = currentMag+ "/" + ammo;
}
public void movePlayer()
{
//float x = Input.GetAxis("Horizontal");
//float y = Input.GetAxis("Vertical");
float x = moveJS.Horizontal;
float y = moveJS.Vertical;
nav.velocity = new Vector3(x * moveSpeed, 0, y * moveSpeed);
if (nav.velocity.x != 0 || nav.velocity.z != 0)
{ animator.SetBool("isRunning", true); }
else { animator.SetBool("isRunning", false); }
}
public void playerShoot()
{
bool isAiming = false;
float x = shootJS.Horizontal; float z = shootJS.Vertical;
if (x != 0 || z != 0)
{
isAiming = true;
/* Vector3 lookDir = new Vector3(x, 0, z);
Quaternion lookRotation = Quaternion.LookRotation(lookDir, Vector3.up);
float step = rotationSpeed * Time.deltaTime;
player.transform.rotation = Quaternion.RotateTowards(lookRotation, transform.rotation, step);*/
float myAngle = Mathf.Atan2(x, z) * Mathf.Rad2Deg;
float bodyRotation = myAngle + player.transform.eulerAngles.y;
player.transform.Rotate( 0,myAngle,0,Space.World);
}
else { shoot();isAiming = false; }
}
void shoot()
{
if (currentMag > 0)
{
Instantiate(bullet, shotSpawn.position, shotSpawn.rotation);
currentMag--;
}
else if (currentMag=0)
{
StartCoroutine(reload());
}
else
return;
}
IEnumerator reload()
{
ammo = ammo - mag;
currentMag = mag;
yield return new WaitForSeconds(reloadTime);
}
}

well you are calling every frame playerShoot() -> not moving -> shoot().
And in the same way also playerShoot() -> not moving -> player.transform.Rotate( 0,myAngle,0,Space.World);.
I think what you rather should do is
doing the shoot only in the very first frame where both inputs are 0
for the move rather set the rotation instead of increasing it
Something like
private bool lastFrameMoved;
public void playerShoot()
{
float x = shootJS.Horizontal;
float z = shootJS.Vertical;
if (x != 0 || z != 0)
{
var lookDir = new Vector3(x, 0, z);
var lookRotation = Quaternion.LookRotation(lookDir, Vector3.up);
player.transform.rotation = lookRotation;
lastFrameMoved = true;
}
else
{
if(lastFrameMoved)
{
shoot();
}
lastFrameMoved = false;
}
}

I solved the look rotation in Bolt (because it helps me visualize). I'll solve the shoot part soon. I'm using the wonderful Joystick Pack by Fenerax Studios.
https://assetstore.unity.com/publishers/32730

Related

Unity grappling more like Tarzan

I am trying to make a grappling hook more fluent but as of right now it is very choppy and does not have the right feel. It currently makes a line and pulls the player there. I have not tried anything yet because I am not even sure we're to start on fixing this. Here is all the grappling code below. `using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(SFPSC_PlayerMovement))] // PlayerMovement also requires Rigidbody
public class SFPSC_GrapplingHook : MonoBehaviour
{
public bool IsGrappling
{
get { return isGrappling; }
}
private SFPSC_PlayerMovement pm;
private Rigidbody rb;
private int segments;
private void Start()
{
segments = rope.segments;
pm = this.GetComponent<SFPSC_PlayerMovement>();
rb = this.GetComponent<Rigidbody>();
}
private bool isGrappling = false;
private void Update()
{
if (crossHairSpinningPart != null)
{
// we need 2 raycasts bc w/ 1 you can grapple through colliders which isn't good
if (Physics.Raycast(SFPSC_FPSCamera.cam.transform.position, SFPSC_FPSCamera.cam.transform.forward, out hitInfo, maxGrappleDistance, layerMask))
{
hitName = hitInfo.collider.name;
if (Physics.Raycast(SFPSC_FPSCamera.cam.transform.position, SFPSC_FPSCamera.cam.transform.forward, out hitInfo, maxGrappleDistance))
{
if (hitName != hitInfo.collider.name)
goto _else;
crossHairSpinningPart.gameObject.SetActive(true);
crossHairSpinningPart.Rotate(Vector3.forward * crossHairSpinSpeed * Time.deltaTime);
goto _out;
}
}
_else:
crossHairSpinningPart.gameObject.SetActive(false);
}
_out:
if (!isGrappling)
{
if (Input.GetKeyDown(SFPSC_KeyManager.Grapple))
Grapple();
return;
}
else
{
if (!Input.GetKey(SFPSC_KeyManager.Grapple))
UnGrapple();
GrappleUpdate();
return;
}
}
[Header("Properties")]
public float maxGrappleDistance = 100.0f;
public SFPSC_Rope rope;
public float maximumSpeed = 100.0f;
public float deceleration = 2500.0f; // This is how much the player is going to decelerate after stopped grappling
public float deceleratingTime = 1.4f; // This is the time the decelerating is going to act on the player after stopped grappling
public RectTransform crossHairSpinningPart;
public float crossHairSpinSpeed = 200.0f;
public float distanceToStop = 2.0f;
public LayerMask layerMask;
public float grappleCooldown = 1.0f;
private bool isBlocked = false;
private Transform location; // the grappled location
private RaycastHit hitInfo;
private string hitName;
public void Grapple()
{
if (isBlocked)
return;
// we need 2 raycasts bc w/ 1 you can grapple through colliders which isn't good
if (Physics.Raycast(SFPSC_FPSCamera.cam.transform.position, SFPSC_FPSCamera.cam.transform.forward, out hitInfo, maxGrappleDistance, layerMask))
{
hitName = hitInfo.collider.name;
if (Physics.Raycast(SFPSC_FPSCamera.cam.transform.position, SFPSC_FPSCamera.cam.transform.forward, out hitInfo, maxGrappleDistance))
{
if (hitName != hitInfo.collider.name)
return;
// We create a GameObject and we parent it to the grappled object.
// If we don't parent it to the object and the object moves the player is stuck only on one location instead of the moving object.
location = new GameObject().transform;//Instantiate(new GameObject(), hitInfo.point, Quaternion.identity).transform;
location.position = hitInfo.point;
location.parent = hitInfo.collider.transform;
if (decelerateTimer != 0.0f)
StopCoroutine(Decelerate());
pm.DisableMovement();
// Rope attaching
rope.segments = (int)((hitInfo.distance / maxGrappleDistance) * segments);
rope.Grapple(transform.position, hitInfo.point);
rb.useGravity = false;
isGrappling = true;
}
}
}
private Vector3 grappleForce;
public void UnGrapple()
{
if (!isGrappling)
return;
if (location != null)
Destroy(location.gameObject);
if (decelerateTimer == 0.0f)
StartCoroutine(Decelerate());
else
decelerateTimer = 0.0f;
pm.EnableMovement();
// Rope detaching
rope.UnGrapple();
Invoke("UnblockGrapple", grappleCooldown);
rb.useGravity = true;
isGrappling = false;
}
private void UnblockGrapple()
{
isBlocked = false;
}
private float decelerateTimer = 0.0f, max;
private IEnumerator Decelerate()
{
WaitForEndOfFrame wfeof = new WaitForEndOfFrame();
max = deceleratingTime * Mathf.Clamp01(targetDistance / 10.0f) * Mathf.Clamp01(rb.velocity.magnitude / 30.0f);
for (; decelerateTimer < max; decelerateTimer += Time.deltaTime)
{
rb.AddForce(-rb.velocity.normalized * deceleration * (1.0f - decelerateTimer / max) * Mathf.Clamp01(rb.velocity.sqrMagnitude / 400.0f) * Time.deltaTime, ForceMode.Acceleration);
yield return wfeof;
}
decelerateTimer = 0.0f;
}
private Vector3 dir;
private float speed = 0.0f, targetDistance;
private void GrappleUpdate()
{
if (location == null)
return;
targetDistance = Vector3.Distance(transform.position, location.position);
rope.segments = (int)((targetDistance / maxGrappleDistance) * segments);
dir = (location.position - transform.position).normalized;
rb.velocity = Vector3.Lerp(rb.velocity, dir * maximumSpeed * Mathf.Clamp01(targetDistance / (4.0f * distanceToStop)), Time.deltaTime);
// Rope updating
rope.UpdateStart(transform.position);
rope.UpdateGrapple();
}
private Vector3 ClampMag(Vector3 vec, float maxMag)
{
if (vec.sqrMagnitude > maxMag * maxMag)
vec = vec.normalized * maxMag;
return vec;
}
}
`
Try using FixedUpdate instead of Update for physics based work (basically all of your code in Update right now). Update is dependent on your computer's clock speed and refresh rate (more or less), and gets called at fairly irregular intervals, because the next update is called in the next frame, after the present frame has finished processing. FixedUpdate makes it frame-rate independent.
Also, you can cap your framerate using Application.targetFrameRate and cap it to a decent FPS.
You could also multiply your movement with Time.deltaTime for smoother movement, although this is a standard practice and yet debatable for use as a smoothing value.

How do i make it so my character/camera stops moving when UI is open?

I just need to add to it to make the character movement/camera stop moving when the UI is open for the quest, but I don't get where to put the code for the bool variable. And then put to write for the code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class QuestGiver : MonoBehaviour
{
public Quest quest;
public GameObject questWindow;
public Text titleText;
public Text descriptionText;
public Movement2 player;
public void OpenQuestWindow()
{
questWindow.SetActive(true);
titleText.text = quest.title;
descriptionText.text = quest.description;
}
public void AcceptQuest()
{
questWindow.SetActive(false);
quest.isActive = true;
player.quest = quest;
}
void Start()
{
questWindow = GameObject.Find("QuestWindow");
questWindow.SetActive(false);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement2 : MonoBehaviour
{
[SerializeField] CharacterController controller;
private Vector3 playerVelocity;
private bool groundedPlayer;
public float playerSpeed = 5.0f;
private float jumpHeight = 40f;
public float gravityValue = -9.81f;
public Transform Cam;
public KeyCode jump;
public KeyCode FlyUp;
public KeyCode FlyDown;
public bool ablefly;
private float FlyMax = 250f;
public Quest quest;
public int SoulHP = 30;
private void Start()
{
// add character controller
// controller = gameObject.AddComponent<CharacterController>();
}
void Update()
{
// check if the player is grounded and the vector3.y < 0, if one of this condition is true set back the playerVelocity.y = 0f;
groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector3 flyup = new Vector3(0, 50, 0);
Vector3 flydown = new Vector3(0, -50, 0);
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
// Look for the camera y Rotation and multiply it for the vector 3 move in order make the player direction y as same as the camera.
Vector3 FollowCam = Quaternion.Euler(0, Cam.eulerAngles.y, 0) * move;
controller.Move(FollowCam * Time.deltaTime * playerSpeed);
// makes the player jump by adding a float value to the vector 3 y
if (Input.GetKeyDown(jump) && ablefly == false && groundedPlayer == true)
{
playerVelocity.y += 4f;
//print("Diocane");
}
if (Input.GetKeyDown(FlyUp) && ablefly == true)
{
//flyup = Vector3.ClampMagnitude(flyup, 250f);
gravityValue = 0;
controller.Move(flyup * Time.deltaTime * playerSpeed);
}
if (Input.GetKeyDown(FlyDown) && ablefly == true)
{
//flyup = Vector3.ClampMagnitude(flyup, 250f);
gravityValue = 0;
controller.Move(flydown * Time.deltaTime * playerSpeed);
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
}
public void GoFind()
{
if (quest.isActive)
{
quest.goal.ItemCollected();
if (quest.goal.IsReached())
SoulHP += 30;
}
}
}
You could set the Time.timeScale to 0 when the ui is opened to make anything using deltaTime stop moving.
In the OpenQuestWindow() you would add Time.timeScale = 0;
and in the AcceptQuest() method add Time.timeScale = 1; to set it back to normal
This looks like a Similar question. please check this and ask me if you don't get that.
EDIT:
This is not a tested code, but I hope will give you an idea, of how to proceed.
1- define a public bool variable mybool in Movement2 script
2- call that bool in the QuestGiver Script like this:
void Start() {
questWindow = GameObject.Find("QuestWindow");
questWindow.SetActive(false);
player.mybool = false; // or get the player gameobject by tag...
}
update your Movement2 update function to this:
void Update() {
if (mybool) {
// check if the player is grounded and the vector3.y < 0, if one of this condition is true set back the playerVelocity.y = 0f;
groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0) {
playerVelocity.y = 0 f;
}
Vector3 flyup = new Vector3(0, 50, 0);
Vector3 flydown = new Vector3(0, -50, 0);
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
// Look for the camera y Rotation and multiply it for the vector 3 move in order make the player direction y as same as the camera.
Vector3 FollowCam = Quaternion.Euler(0, Cam.eulerAngles.y, 0) * move;
controller.Move(FollowCam * Time.deltaTime * playerSpeed);
// makes the player jump by adding a float value to the vector 3 y
if (Input.GetKeyDown(jump) && ablefly == false && groundedPlayer == true) {
playerVelocity.y += 4 f;
//print("Diocane");
}
if (Input.GetKeyDown(FlyUp) && ablefly == true) {
//flyup = Vector3.ClampMagnitude(flyup, 250f);
gravityValue = 0;
controller.Move(flyup * Time.deltaTime * playerSpeed);
}
if (Input.GetKeyDown(FlyDown) && ablefly == true) {
//flyup = Vector3.ClampMagnitude(flyup, 250f);
gravityValue = 0;
controller.Move(flydown * Time.deltaTime * playerSpeed);
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
}
if (!camMove) {
Vector3 move = new Vector3(0, 0, 0);
}
}
Now update that bool in QuestGiver:
public void OpenQuestWindow()
{
questWindow.SetActive(true);
titleText.text = quest.title;
descriptionText.text = quest.description;
player.mybool = false;
}
public void AcceptQuest()
{
questWindow.SetActive(false);
quest.isActive = true;
player.quest = quest;
player.mybool = true;
}

How can I add a slowdown effect when object is getting close to a target?

using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.AI;
public class Waypoints : UnityEngine.MonoBehaviour
{
public List<Transform> waypoints = new List<Transform>();
public float movementSpeed = 5.0f;
public float slowdownSpeed = 1f;
public float rotationSpeed = 2.0f;
public float waypointDistance = 0.1f;
public float slowdownDistance = 7f;
public bool moveBackward = false;
public bool moveLoop = false;
public bool includeTransformPosition = false;
private Transform targetWaypoint;
private int targetWaypointIndex = 0;
private int lastWaypointIndex;
private bool includeTransform = true;
private GameObject go;
// Use this for initialization
void Start()
{
go = new GameObject();
go.transform.position = transform.position;
if (moveBackward && waypoints.Count > 2)
{
lastWaypointIndex = 0;
targetWaypoint = waypoints[waypoints.Count - 1];
}
else
{
lastWaypointIndex = waypoints.Count - 1;
targetWaypoint = waypoints[targetWaypointIndex]; //Set the first target waypoint at the start so the enemy starts moving towards a waypoint
}
}
// Update is called once per frame
void Update()
{
if (includeTransformPosition && includeTransform)
{
waypoints.Insert(0,go.transform);
includeTransform = false;
}
else
{
if (includeTransformPosition == false)
{
waypoints.Remove(go.transform);
includeTransform = true;
}
}
float movementStep = movementSpeed * Time.deltaTime;
float rotationStep = rotationSpeed * Time.deltaTime;
Vector3 directionToTarget = targetWaypoint.position - transform.position;
Quaternion rotationToTarget = Quaternion.LookRotation(directionToTarget);
transform.rotation = Quaternion.Slerp(transform.rotation, rotationToTarget, rotationStep);
float distance = Vector3.Distance(transform.position, targetWaypoint.position);
CheckDistanceToWaypoint(distance);
if(slowdownDistance < 7f)
{
movementSpeed -= movementSpeed * Time.deltaTime;
}
transform.position = Vector3.MoveTowards(transform.position, targetWaypoint.position, movementStep);
}
void CheckDistanceToWaypoint(float currentDistance)
{
if (currentDistance <= waypointDistance)
{
targetWaypointIndex++;
UpdateTargetWaypoint();
}
}
void UpdateTargetWaypoint()
{
if (targetWaypointIndex > lastWaypointIndex)
{
targetWaypointIndex = 0;
}
targetWaypoint = waypoints[targetWaypointIndex];
}
}
At this part I'm trying to slowdown the movement speed but it's not changing the speed at all :
if(slowdownDistance < 7f)
{
movementSpeed -= movementSpeed * Time.deltaTime;
}
What I'm trying to do when the transform start to move increase the speed slowly to some constant speed and then when the transform is getting closer to the waypoint then if the distance is less then 7 decrease the speed down to 0 so the object will stop at the waypoint then after X seconds move back the transform to the transform original position(go.transform) with the same increasing decreasing speed movement.
but I can't even make the first simple slowdown.
you set slowdownDistance to 7, i dont see you ever reducing it below 7 but you have if statement that executes only it it is under 7 do you reduce it elsewhere?
You probably planned to compare slowdownDistance to some distance rather than comparing it to its own value.
If you want to slow down the whole scene you could use a:
while(distance < range)
{
Time.timeScale = 1 - (distance / value);
}
with this you can change the value and so when the player come close time will be slown down mostly.
With the same idea you can do:
while(distance < range)
{
speed = speedInitial - (distance / value);
}
If you want to change just the speed of the player

How do I assign a new transform.position for a GameObject that's triggered by an OnTriggerEnter in Unity?

I have code in my PlayerScript that, on collision with the floor game object (which I've tagged with "FloorTag"), decrements a variable called "Lives." Lives is decrementing, so I know the collision is registering (and everything is tagged correctly). However, I also want the Player game object's position to be reset to a specific Vector3 I've declared when it collides with the floor. For some reason, though, it's not doing this. Where have I gone wrong?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerScript : MonoBehaviour
{
public int Lives;
public Text LivesText;
public int Points;
public Text PointsText;
public Text GameOverText;
public CharacterController CharController;
public float moveSpeed = 9;
public float rotSpeed = 85;
float yVelocity = 0;
public float jumpForce = 2.5f;
public float gravityModifier = 0.025f;
bool prevIsGrounded;
Vector3 StartingPlatformCoords = new Vector3 (38, 16, 38);
// Start is called before the first frame update
void Start()
{
Lives = 8;
SetLivesText();
Points = 0;
SetPointsText();
prevIsGrounded = CharController.isGrounded;
//CharController = gameObject.GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
// L-R Forward-Back Motion
float hAxis = Input.GetAxis("Horizontal");
float vAxis = Input.GetAxis("Vertical");
transform.Rotate(0, rotSpeed * Time.deltaTime * hAxis, 0);
Vector3 amountToMove = transform.forward * moveSpeed * Time.deltaTime * vAxis;
// Jump Motion
if (CharController.isGrounded)
{
if (!prevIsGrounded && CharController.isGrounded)
{
yVelocity = 0;
}
if (Input.GetKeyDown(KeyCode.Space))
{
yVelocity = jumpForce;
}
}
else
{
if (Input.GetKeyUp(KeyCode.Space))
{
yVelocity = 0;
}
yVelocity += Physics.gravity.y * gravityModifier;
}
amountToMove.y = yVelocity;
// Modify the y-value within this Vector3 (which contains an x, y, z, and some utility functions like distance etc.) manually
// Final Motion
CharController.Move(amountToMove);
// Update
prevIsGrounded = CharController.isGrounded;
// Camera
Vector3 camPos = transform.position + transform.forward * -10 + Vector3.up * 3;
Camera.main.transform.position = camPos;
Camera.main.transform.LookAt(transform);
//if (Input.GetKeyDown(KeyCode.Space))
//{
//yVelocity = jumpForce;
//}
//yVelocity += Physics.gravity.y * gravityModifier;
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("FloorTag"))
{
transform.position = StartingPlatformCoords;
Lives -= 1;
SetLivesText();
Debug.Log(transform.position);
}
if (other.gameObject.CompareTag("CellTag"))
{
Points += 1;
SetPointsText();
}
}
void SetLivesText()
{
LivesText.text = "Lives: " + Lives.ToString();
if (Lives <= 0)
{
GameOverText.text = "Game Over";
}
}
void SetPointsText()
{
PointsText.text = "Score: " + Points.ToString();
}
}
CharacterController can override changes made to transform.position. Simplest workaround is to disable it, then re-enable it after directly modifying transform.position:
public CharacterController CharController;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("FloorTag"))
{
CharController.enabled = false;
transform.position = StartingPlatformCoords;
CharController.enabled = true;
Lives -= 1;
SetLivesText();
Debug.Log(transform.position);
}
if (other.gameObject.CompareTag("CellTag"))
{
Points += 1;
SetPointsText();
}
}

Infinite Runner Unity2d

So, when I start the game, my character can jump on the first platform (because that is the manually placed platform), but I cannot jump on the spawned floors. BTW I am able to run on the floors and I know my jump works correctly.
I have tried so many ways of collider detection I am going crazy and I know its a simple fix that I just can't figure out.
I expected my character to be able to jump on the duplicated platforms but the character just doesn't do anything at all.
If anyone is willing to take a look that would be very helpful. - Nick
P.S I know my code is messy.
CODE:
#Code that is on my player script#
using System;
using System.Diagnostics;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using TouchControlsKit;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Text;
using System.IO;
public class Attack : MonoBehaviour
{
const float k_GroundedRadius = .2f; // Radius of the overlap circle to determine if grounded
[SerializeField] private LayerMask m_WhatIsGround;
[SerializeField] private Transform m_GroundCheck;
private bool m_Grounded;
public Collider2D objectCollider;
public Collider2D anotherCollider;
[Range(0, .3f)] [SerializeField] private float m_MovementSmoothing = .05f;
private Timer t;
private Timer a;
private float timeStamp;
private float die = 0;
public GameObject bullet;
private bool m_FacingRight = true;
public float move;
private Vector3 velocity = Vector3.zero;
public GameObject idle_0;
public playscript play;
public Transform player;
private Rigidbody2D m_Rigidbody2D;
[SerializeField] private float m_JumpForce = 200f;
bool swing = false;
bool isgrounded = false;
public bool canJump = false;
bool slide = false;
public Transform groundLayer; // Insert the layer here.
public Vector2 jumpHeight;
private Vector2 touchOrigin = -Vector2.one;
public Vector2 moveSpeed;
public bool run;
Collider2D m_Collider;
// variable to hold a reference to our SpriteRenderer component
private SpriteRenderer mySpriteRenderer;
// This function is called just one time by Unity the moment the component loads
private void Awake()
{
// get a reference to the SpriteRenderer component on this gameObject
mySpriteRenderer = GetComponent<SpriteRenderer>();
animator.SetBool("death", false);
}
public Animator animator;
Animator anim;
int swingHash = Animator.StringToHash("swing");
// Use this for initialization
void Start()
{
timeStamp = Time.time + 5;
m_Collider = GetComponent<Collider2D>();
run = false;
m_Rigidbody2D = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
animator.SetBool("isgrounded", false);
isgrounded = false;
canJump = false;
animator.SetBool("swing", false);
}
private void FixedUpdate()
{
m_Grounded = false;
// The player is grounded if a circlecast to the groundcheck position hits anything designated as ground
// This can be done using layers instead but Sample Assets will not overwrite your project settings.
Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
animator.SetBool("isgrounded", true);
m_Grounded = true;
}
}
// Update is called once per frame
void Update()
{
anotherCollider = GameObject.FindGameObjectWithTag("Ground").GetComponent<BoxCollider2D>();
objectCollider = GameObject.FindGameObjectWithTag("Player").GetComponent<CapsuleCollider2D>();
Vector3 targetVelocity = new Vector2(move * 2f, m_Rigidbody2D.velocity.y);
m_Rigidbody2D.velocity = Vector3.SmoothDamp(m_Rigidbody2D.velocity, targetVelocity, ref velocity, m_MovementSmoothing);
animator.SetBool("run", true);
if (move > 0 && !m_FacingRight)
{
// ... flip the player.
Flip();
}
// Otherwise if the input is moving the player left and the player is facing right...
else if (move < 0 && m_FacingRight)
{
// ... flip the player.
Flip();
}
int horizontal = 0; //Used to store the horizontal move direction.
int vertical = 0; //Used to store the vertical move direction.
#if UNITY_STANDALONE || UNITY_WEBPLAYER
//Check if we are running on iOS, Android, Windows Phone 8 or Unity iPhone
#elif UNITY_IOS || UNITY_ANDROID || UNITY_WP8 || UNITY_IPHONE
//Check if Input has registered more than zero touches
if (Input.touchCount > 0)
{
//Store the first touch detected.
Touch myTouch = Input.touches[0];
//Check if the phase of that touch equals Began
if (myTouch.phase == TouchPhase.Began)
{
//If so, set touchOrigin to the position of that touch
touchOrigin = myTouch.position;
}
//If the touch phase is not Began, and instead is equal to Ended and the x of touchOrigin is greater or equal to zero:
else if (myTouch.phase == TouchPhase.Ended && touchOrigin.x >= 0)
{
//Set touchEnd to equal the position of this touch
Vector2 touchEnd = myTouch.position;
//Calculate the difference between the beginning and end of the touch on the x axis.
float x = touchEnd.x - touchOrigin.x;
//Calculate the difference between the beginning and end of the touch on the y axis.
float y = touchEnd.y - touchOrigin.y;
//Set touchOrigin.x to -1 so that our else if statement will evaluate false and not repeat immediately.
touchOrigin.x = -1;
//Check if the difference along the x axis is greater than the difference along the y axis.
if (Mathf.Abs(x) > Mathf.Abs(y))
//If x is greater than zero, set horizontal to 1, otherwise set it to -1
horizontal = x > 0 ? 1 : -1;
else
//If y is greater than zero, set horizontal to 1, otherwise set it to -1
vertical = y > 0 ? 1 : -1;
}
}
#endif
if (TCKInput.GetAction("jumpBtn", EActionEvent.Up))
{
animator.SetBool("jump", false);
}
if (TCKInput.GetAction("jumpBtn", EActionEvent.Down) && m_Grounded == true)
{
animator.SetBool("jump", true);
m_Grounded = false;
m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
}
if (TCKInput.GetAction("fireBtn", EActionEvent.Down))
{
animator.SetBool("swing", true);
m_Collider.enabled = !m_Collider.enabled;
}
if (TCKInput.GetAction("fireBtn", EActionEvent.Up))
{
animator.SetBool("swing", false);
m_Collider.enabled = !m_Collider.enabled;
}
if (TCKInput.GetAction("slideBtn", EActionEvent.Down))
{
if (timeStamp <= Time.time)
{
animator.SetBool("slide", true);
GameObject b = (GameObject)(Instantiate(bullet, transform.position + transform.right * 1.5f, Quaternion.identity));
b.GetComponent<Rigidbody2D>().AddForce(transform.right * 1000);
timeStamp = Time.time + 5;
}
}
if (TCKInput.GetAction("slideBtn", EActionEvent.Up))
{
animator.SetBool("slide", false);
}
if (TCKInput.GetAction("right", EActionEvent.Press))
{
move = -1;
}
if (TCKInput.GetAction("right", EActionEvent.Up))
{
animator.SetBool("run", false);
}
if (TCKInput.GetAction("left", EActionEvent.Press))
{
move = 1;
}
if (TCKInput.GetAction("left", EActionEvent.Up))
{
animator.SetBool("run", false);
}
if (objectCollider.IsTouching(anotherCollider))
{
canJump = true;
}
else
{
canJump = false;
}
}
private void Flip()
{
// Switch the way the player is labelled as facing.
m_FacingRight = !m_FacingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
void Hurt()
{
move = 4;
SceneManager.LoadScene(0);
}
protected void OnCollisionEnter2D(Collision2D collision)
{
EnemyHealth3 enemy = collision.collider.GetComponent<EnemyHealth3>();
if (enemy != null)
{
move = 0;
animator.SetBool("death", true);
m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
StartCoroutine(ExecuteAfterTime(.1));
}
}
IEnumerator ExecuteAfterTime(double time)
{
yield return new WaitForSeconds((float)time);
Hurt();
}
}
#Code that is on the floor spawner script#
using UnityEngine;
using System.Collections;
public class Floor_Spawn_Script : MonoBehaviour
{
public GameObject[] obj;
private float oldPosition;
private float currentPosition;
private float ctr = 0;
private float inte = 10.19f;
// Use this for initialization
private void Start()
{
oldPosition = transform.position.x;
AddRoom(ctr * inte);
ctr += 1;
AddRoom(ctr * inte);
ctr += 1;
AddRoom(ctr * inte);
}
// Update is called once per frame
void Update()
{
currentPosition = transform.position.x;
if ((currentPosition - oldPosition) <= 9.595f)
{
AddRoom(ctr * inte);
oldPosition = transform.position.x;
ctr += 1;
}
}
void AddRoom(float roomCenter)
{
GameObject room = (GameObject)Instantiate(obj[Random.Range(0, obj.Length)]);
room.transform.position = new Vector3(roomCenter, 0f, 10f);
}
}```

Categories

Resources