How can i make the player idle when not moving the mouse? - c#

When i'm moving the mouse around the player is walking facing to the mouse cursor.
Now i want to make that if i'm not moving the mouse to make the player idle.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WorldInteraction : MonoBehaviour
{
public int speed = 5; // Determines how quickly object moves towards position
public float rotationSpeed = 5f;
private Animator _animator;
private bool toMove = true;
private Vector3 tmpMousePosition;
UnityEngine.AI.NavMeshAgent playerAgent;
private void Start()
{
tmpMousePosition = Input.mousePosition;
_animator = GetComponent<Animator>();
_animator.CrossFade("Idle", 0);
playerAgent = GetComponent<UnityEngine.AI.NavMeshAgent>();
}
private void Update()
{
if (Input.GetMouseButtonDown(0) && toMove == false &&
!UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
{
toMove = true;
}
if (Input.GetMouseButtonDown(1) && toMove == true)
{
toMove = false;
}
if (toMove == true)
{
GetInteraction();
}
}
void GetInteraction()
{
if (tmpMousePosition != Input.mousePosition)
{
tmpMousePosition = Input.mousePosition;
_animator.CrossFade("Walk", 0);
Ray interactionRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit interactionInfo;
if (Physics.Raycast(interactionRay, out interactionInfo, Mathf.Infinity))
{
GameObject interactedObject = interactionInfo.collider.gameObject;
if (interactedObject.tag == "Interactable Object")
{
interactedObject.GetComponent<Interactable>().MoveToInteraction(playerAgent);
}
else
{
playerAgent.destination = interactionInfo.point;
}
}
}
else
{
_animator.CrossFade("Idle", 0);
}
}
}
I'm using the variable tmpMousePosition to check if the mouse is in a move or not. The problem is when it's on a move and the player is in "Walk" mode the player is stuttering each a second or so.
The idea is when the mouse is moving then move the player when the mouse is not moving make the player in Idle.
In the Update function i'm using a bool to stop/continue the interaction like a switch with the mouse left/right buttons. But now i want to use the mouse movement to Walk/Idle the player.

Just get the movement through Input.GetAxis("Mouse X") and if it's not moving , play Idle

Related

Stopping player's movement upon clicking dialogue - Unity

I have a problem where when I click the dialogue while passing through an NPC or while moving, the character will continue moving in the direction of the joystick before it is set active to false.
I have tried setting the horizontal and vertical input to zero and even the movement direction which is the calculated horizontal and vertical input, but the character still moves in the last direction it was moving. I'm not sure if the if statement that I created is correct but that was the idea that came to mind.
This is the script for the movement of the player:
using UnityEngine;
using UnityEngine.EventSystems;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private GameObject interactButton;
public float speed, rotationSpeed, ySpeed, originalStepOffset;
public Joystick joystick;
private Animator animator;
private CharacterController characterController;
void Start()
{
animator = GetComponent<Animator>();
characterController = GetComponent<CharacterController>();
originalStepOffset = characterController.stepOffset;
}
// Update is called once per frame
void FixedUpdate()
{
float horizontalInput = joystick.Horizontal;
float verticalInput = joystick.Vertical;
Vector3 movementDirection = new Vector3(horizontalInput, 0, verticalInput);
movementDirection = Quaternion.Euler(0, 45f, 0) * movementDirection;
float magnitude = Mathf.Clamp01(movementDirection.magnitude) * speed;
movementDirection.Normalize();
ySpeed += Physics.gravity.y * Time.deltaTime;
if(characterController.isGrounded)
{
characterController.stepOffset = originalStepOffset;
ySpeed = -0.5f;
}
else
{
characterController.stepOffset = 0;
}
Vector3 velocity = movementDirection * magnitude;
velocity = AdjustVelocityToSlope(velocity);
velocity.y += ySpeed;
//transform.Translate(movementDirection * speed * Time.deltaTime, Space.World);
characterController.Move(velocity * Time.deltaTime);
if (movementDirection != Vector3.zero)
{
if(EventSystem.current.currentSelectedGameObject != null)
{
if (EventSystem.current.currentSelectedGameObject.name == "InteractButton")
{
horizontalInput = 0f;
verticalInput = 0f;
movementDirection = Vector3.zero;
animator.SetBool("IsMoving", false);
}
else
{
//transform.forward = movementDirection;
animator.SetBool("IsMoving", true);
Quaternion toRotation = Quaternion.LookRotation(movementDirection, Vector3.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
}
}else
{
animator.SetBool("IsMoving", true);
Quaternion toRotation = Quaternion.LookRotation(movementDirection, Vector3.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
}
} else
{
animator.SetBool("IsMoving", false);
}
}
private Vector3 AdjustVelocityToSlope(Vector3 velocity)
{
var ray = new Ray(transform.position, Vector3.down);
if(Physics.Raycast(ray, out RaycastHit hitInfo, 0.2f))
{
var slopeRotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
var adjustedVelocity = slopeRotation * velocity;
if(adjustedVelocity.y < 0)
{
return adjustedVelocity;
}
}
return velocity;
}
}
The function that will make the button to set active to true and add its onclick listeners is a trigger enter function and a trigger exit for setting it active to false and removing the onclick listeners. It is attached to multiple NPC whenever I go near them, the button will appear. In case someone needs to see the script for the button here it is, but I'm gonna paste only until the related part:
using System;
using System.Collections;
using System.Drawing;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[System.Serializable]
public class DialogueManager : MonoBehaviour
{
/*
// NPC INTERACTION
private static DialogueManager buttonOwner;
private Camera mainCamera;
*/
// NPC DATA
private Character characterJson;
// FOR DIALOG FLOW
private int multiDialogCycle;
public static int dialogId;
// GAME OBJECTS REFERENCE
[SerializeField] private GameObject dialogBox, addPanel, m1, id, darkPanel;
[SerializeField] private Button nameBtn, choiceOneBtn, choiceTwoBtn;
[SerializeField] private TextMeshProUGUI npcName, choiceOne, choiceTwo, dialogName, dialogMessage, addedText;
[SerializeField] private TextAsset characterData;
// FOR MULTIPLE DIALOGUES WITHOUT CHOICES
private bool clickEnable;
private string[] multiDialog;
// CHOICES STORAGE
private static Choice[] choices = new Choice[2];
//private TryInstantiate tryInstantiate = new TryInstantiate();
private GameData gameData;
private void Start()
{
// LOAD NPC DATA
characterJson = JsonUtility.FromJson<Character>(characterData.text);
// SET DEFAULT VALUE
//dialogId = 0;
multiDialogCycle = 0;
clickEnable = false;
// SET SCRIPTABLE OBJECT FOR DATA STORAGE
gameData = Resources.Load<GameData>("GameData/GameData");
}
private void Update()
{
if(nameBtn.gameObject.activeInHierarchy)
{
if(Input.GetKey(KeyCode.Space))
{
EventSystem.current.SetSelectedGameObject(nameBtn.gameObject);
}
}
// FOR ENDING DIALOGUES WITHOUT CHOICES
if (Input.GetMouseButtonDown(0) && clickEnable == true)
{
if (multiDialog.Length > 1 )
{
if(getDialog(dialogId).choices.Length == 0 && multiDialogCycle == multiDialog.Length - 1)
{
addArticles();
addObjectives();
addClues();
closeDialog();
Debug.Log(getDialog(dialogId).minigame);
}
else
{
if(getDialog(dialogId).minigame != "" && multiDialogCycle < multiDialog.Length - 1)
{
if(!gameData.idShown)
{
darkPanel.SetActive(true);
id.SetActive(true);
}
}else
{
multiDialogCycle++;
loadCharacterData();
}
}
}
else
{
if (getDialog(dialogId).minigame != "")
{
if(getDialog(dialogId).minigame == "spot_object")
{
m1.SetActive(true);
}
dialogBox.SetActive(false);
gameData.dialogActive = false;
}
else
{
addArticles();
addObjectives();
addClues();
closeDialog();
}
}
}
if(gameData.idShown)
{
multiDialogCycle++;
loadCharacterData();
gameData.idShown = false;
}
if (gameData.dialogActive && dialogId != 0 && getDialog(dialogId).minigame != "" && !gameData.loadedData)
{
updateID();
loadCharacterData();
}
// FOR NPC NAMES
/*
if (buttonOwner != this) return;
if (!mainCamera) mainCamera = Camera.main;
var position = mainCamera.WorldToScreenPoint(head.position + offset);
//uiUse.transform.position = position;
nameBtn.transform.position = position;
*/
}
private void OnTriggerEnter(Collider collisionInfo)
{
if (collisionInfo.CompareTag("Player"))
{
nameBtn.gameObject.SetActive(true);
nameBtn.GetComponent<Image>().sprite = Resources.Load<Sprite>("InteractionAsset/DIALOGUE");
nameBtn.transform.GetChild(0).GetComponent<TextMeshProUGUI>().color = new Color32(75,75,75,255);
//buttonOwner = this;
nameBtn.onClick.RemoveListener(onNameClick);
nameBtn.onClick.AddListener(onNameClick);
choiceOneBtn.onClick.RemoveListener(onChoiceClick);
choiceOneBtn.onClick.AddListener(onChoiceClick);
choiceTwoBtn.onClick.RemoveListener(onChoiceClick);
choiceTwoBtn.onClick.AddListener(onChoiceClick);
npcName.text = characterJson.name;
}
}
private void OnTriggerExit(Collider collisionInfo)
{
if (collisionInfo.CompareTag("Player"))
{
nameBtn.onClick.RemoveListener(onNameClick);
choiceOneBtn.onClick.RemoveListener(onChoiceClick);
choiceTwoBtn.onClick.RemoveListener(onChoiceClick);
nameBtn.gameObject.SetActive(false);
//buttonOwner = null;
}
}
// DIALOGUE SYSTEM
public void onNameClick()
{
nameBtn.gameObject.SetActive(false);
dialogBox.SetActive(true);
gameData.dialogActive = true;
FindObjectOfType<AudioManager>().Play("ButtonSound");
if (dialogBox.activeInHierarchy)
{
if (dialogMessage != null && dialogName != null)
{
loadCharacterData();
interactedNPC();
}
else
{
// Debug.Log("null dialog message");
}
}
}
public void updateID()
{
if (gameData.win && !gameData.loadedData)
{
dialogId = gameData.targetId_1;
gameData.loadedData = true;
}
else if (!gameData.win && !gameData.loadedData)
{
dialogId = gameData.targetId_2;
gameData.loadedData = true;
}
}
How can I atleast reset the Joystick's position. I am currently using the Joystick Pack from Unity Asset Store.
I for one would start the Conversation flow from the dialogue step. Once the dialog starts, you can either set a bool or any other type of property (even a referenced object such as the dialogue itself or the NPC that it's chatting to, but a bool is simpler) that would be a marker. Simply put: public bool IsTalking;. This could be in PlayerMovement or the main Player-like component (or SO) which you can access from PlayerMovement via GameObject or a different public variable.
Next, once the dialogue mechanism starts, you can set the marker (such as the bool or NPC ref) in the Player-like component or PlayerMovement to true, false when the chatting stops.
Then in PlayerMovement.FixedUpdate() you can just stop code execution:
// Update is called once per frame
void FixedUpdate()
{
// or if (Player.IsTalking == true) if you want the marker there,
// but you can have it inside PlayerMovement if you wish as long as
// you can reference it without overhead - meaning don't do crazy
// stuff like searching all game objects/components for PlayerMovement)
if (IsTalking == true)
{
if (characterController != null)
characterController.Move(Vector3.zero);
if (animator != null)
animator.SetBool("IsMoving", false);
return;
}
// everything starts executing once the player stops talking to NPCs
float horizontalInput = joystick.Horizontal;
float verticalInput = joystick.Vertical;
Vector3 movementDirection = new Vector3(horizontalInput, 0, verticalInput);
movementDirection = Quaternion.Euler(0, 45f, 0) * movementDirection;
float magnitude = Mathf.Clamp01(movementDirection.
As I understood you dialogue window is modal. Depending on your needs you can stop the internal increment of time progression with
Time.timeScale = 0f;
But this will stop e.g. (UI) animations and the proper function of the event system, so some people use
Time.timeScale = 0.0001f;
This has the drawback that the gameplay continues slowly and our player hero could be hit by a very slow rocket while the user was resting in a pause screen.

AI wandering state doesn't seem to work right

I've been trying to make an AI system that would follow specific waypoints and once the player character walks into the trigger zone, the AI would start chasing the character and vice versa.
It seems that this does kind of work, but the AI only moves to one waypoint and then stops until the player walks into the trigger zone; after which if the player walks out, it again only goes to one waypoint then stops again.
I have multiple waypoints and I just want it to keep cycling through them, but it just goes to one of them and stops.
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEditor;
using UnityEngine;
using UnityEngine.AI;
using UnityEngineInternal;
public class AILocomotion : MonoBehaviour
{
public Transform playerTransform;
NavMeshAgent agent;
Animator animator;
public float maxTime = 1.0f;
public float maxDistance = 1.0f;
float timer = 0.0f;
bool moveTowards = false;
bool followWaypoint = false;
float deaccel= 0.5f;
float calVelocity = 0.0f;
public Transform[] points;
private int destPoint = 0;
public string animState;
void Start()
{
agent = GetComponent<NavMeshAgent>();
animator = GetComponent<Animator>();
moveTowards = false;
followWaypoint = true;
}
// Update is called once per frame
void Update()
{
if (moveTowards == true)
{
timer -= Time.deltaTime;
if (timer < 0.0f)
{
float sqDistance = (playerTransform.position - agent.destination).sqrMagnitude;
if (sqDistance > maxDistance * maxDistance)
{
agent.destination = playerTransform.position;
}
}
animator.SetFloat("Speed", agent.velocity.magnitude);
}
else if (!moveTowards && agent.velocity.magnitude>0.0f)
{
calVelocity = agent.velocity.magnitude;
calVelocity -= Time.deltaTime * deaccel;
animator.SetFloat("Speed", calVelocity);
}
//CHECKS IF BOTH CONDITIONS HAVE MET AND RUNS THE WAYPOINT FOLLOWING CODE
if (followWaypoint == true && (!agent.pathPending && agent.remainingDistance < 1.0f))
{
GotoNextPoint();
}
Debug.LogError("Bool" + followWaypoint);
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
moveTowards = true;
//DISABLES THE WAYPOINT FOLLOWING CODE TO RUN THE CHASE CODE INSTEAD
followWaypoint = false;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
moveTowards = false;
//RE-ENABLES THE WAYPOINT FOLLOWING CODE ONCE THE PLAYER LEAVES THE TRIGGER AREA
followWaypoint = true;
}
}
//THIS IS THE WAYPOINT FOLLOWING CODE
void GotoNextPoint()
{
animator.SetFloat("Speed", agent.velocity.magnitude);
// Returns if no points have been set up
if (points.Length == 0)
return;
// Set the agent to go to the currently selected destination.
agent.destination = points[destPoint].position;
Debug.LogError("DestPoint = " + destPoint);
// Choose the next point in the array as the destination.
// cycling to the start if necessary.
destPoint = Random.Range(0, points.Length);
}
}
Use OnTriggerStay instead of OntriggerEnter and Try

Grappling to grapling point + offset

I'm making a simple game in Unity in 2d. So I have the player and I have a grappler gun. And when I press the right mouse button and the mouse position is in the direction of any object it will grappler to this object. But my question is, I have a small circle (Grappling point) and it is very hard to put the mouse to the grappler point circle direction in the air. so can I add any offset f.e. when my mouse direction from the player is 2 units from the grappler point circle it will still grappler but automatically the grappler line will connect with the grappler point circle. Here is my grappler code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Grappler: MonoBehaviour
{
public LineRenderer Line;
DistanceJoint2D Joint;
Vector3 TargetPos;
RaycastHit2D Hit;
public float Distance = 10f;
public LayerMask Mask;
public float Step = 0f;
void Start()
{
Joint = GetComponent<DistanceJoint2D>();
Joint.enabled = false;
Line.enabled = false;
}
void Update()
{
if(Joint.distance > 1f)
{
Joint.distance -= Step;
}else
{
Line.enabled = false;
Joint.enabled = false;
}
if(Input.GetMouseButtonDown(1))
{
TargetPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
TargetPos.z = 0;
Hit = Physics2D.Raycast(transform.position, TargetPos - transform.position, Distance, Mask);
if (Hit.collider != null && Hit.collider.gameObject.GetComponent<Rigidbody2D>() != null)
{
Joint.enabled = true;
Joint.connectedBody = Hit.collider.gameObject.GetComponent<Rigidbody2D>();
Joint.distance = Vector3.Distance(transform.position, Hit.point);
Line.enabled = true;
Line.SetPosition(0, transform.position);
Line.SetPosition(1, Hit.point);
}
}
if (Input.GetMouseButton(1))
{
Line.SetPosition(0, transform.position);
}
if (Input.GetMouseButtonUp(1))
{
Joint.enabled = false;
Line.enabled = false;
}
}
}
Any ideas?? Thanks
It sounds like you should simply make your collision bigger by 2 units (if that's the amount you want to cheat by). And then instead of using the ray trace hit location, use the location of the object you hit instead.

(Unity C#) NPC not moving on Grass and other terrain

I have created a NPC that follows the main player. When the player is in a certain range of the NPC, the NPC is supposed to walk, run, and attack based on the distance between the player and the NPC. The NPC has an Animator, box collider, Nav Mesh Agent, Enemy Animator And Enemy Controller Script attached. The settings are as follows,
My problem is that the NPC does not chase the player if there's some sort of grass or ferns on the terrain.
The NPC is set to run all types of terrain using Nav Mesh Agent, moreover the bake settings are like in the image. A video of the issue can be seen here.
The code of the enemy controller (although I doubt that is the issue) is as follows:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public enum EnemyState
{
PATROL,
CHASE,
ATTACK
}
public class EnemyController : MonoBehaviour
{
private EnemyAnimator enemy_Anim;
private NavMeshAgent navAgent;
private EnemyState enemy_State;
public float walk_Speed = 0.5f;
public float run_Speed = 4f;
public float chase_Distance = 7f;
private float current_Chase_Distance;
public float attack_Distance = 1.8f;
public float chase_After_Attack_Distance = 2f;
public float patrol_Radius_Min = 20f, patrol_Radius_Max = 60f;
public float patrol_For_This_Time = 15f;
private float patrol_Timer;
public float wait_Before_Attack = 2f;
private float attack_Timer;
private Transform target;
public GameObject attack_Point;
//private EnemyAudio enemy_Audio;
void Awake()
{
enemy_Anim = GetComponent<EnemyAnimator>();
navAgent = GetComponent<NavMeshAgent>();
target = GameObject.FindWithTag(Tags.PLAYER_TAG).transform;
// enemy_Audio = GetComponentInChildren<EnemyAudio>();
}
// Use this for initialization
void Start()
{
enemy_State = EnemyState.PATROL;
patrol_Timer = patrol_For_This_Time;
// when the enemy first gets to the player
// attack right away
attack_Timer = wait_Before_Attack;
// memorize the value of chase distance
// so that we can put it back
current_Chase_Distance = chase_Distance;
}
// Update is called once per frame
void Update()
{
if (enemy_State == EnemyState.PATROL)
{
Patrol();
}
if (enemy_State == EnemyState.CHASE)
{
Chase();
}
if (enemy_State == EnemyState.ATTACK)
{
Attack();
}
}
void Patrol()
{
// tell nav agent that he can move
navAgent.isStopped = false;
navAgent.speed = walk_Speed;
// add to the patrol timer
patrol_Timer += Time.deltaTime;
if (patrol_Timer > patrol_For_This_Time)
{
SetNewRandomDestination();
patrol_Timer = 0f;
}
if (navAgent.velocity.sqrMagnitude > 0)
{
enemy_Anim.Walk(true);
}
else
{
enemy_Anim.Walk(false);
}
// test the distance between the player and the enemy
if (Vector3.Distance(transform.position, target.position) <= chase_Distance)
{
enemy_Anim.Walk(false);
enemy_State = EnemyState.CHASE;
// play spotted audio
// enemy_Audio.Play_ScreamSound();
}
} // patrol
void Chase()
{
// enable the agent to move again
navAgent.isStopped = false;
navAgent.speed = run_Speed;
// set the player's position as the destination
// because we are chasing(running towards) the player
navAgent.SetDestination(target.position);
if (navAgent.velocity.sqrMagnitude > 0)
{
enemy_Anim.Run(true);
}
else
{
enemy_Anim.Run(false);
}
// if the distance between enemy and player is less than attack distance
if (Vector3.Distance(transform.position, target.position) <= attack_Distance)
{
// stop the animations
enemy_Anim.Run(false);
enemy_Anim.Walk(false);
enemy_State = EnemyState.ATTACK;
// reset the chase distance to previous
if (chase_Distance != current_Chase_Distance)
{
chase_Distance = current_Chase_Distance;
}
}
else if (Vector3.Distance(transform.position, target.position) > chase_Distance)
{
// player run away from enemy
// stop running
enemy_Anim.Run(false);
enemy_State = EnemyState.PATROL;
// reset the patrol timer so that the function
// can calculate the new patrol destination right away
patrol_Timer = patrol_For_This_Time;
// reset the chase distance to previous
if (chase_Distance != current_Chase_Distance)
{
chase_Distance = current_Chase_Distance;
}
} // else
} // chase
void Attack()
{
navAgent.velocity = Vector3.zero;
navAgent.isStopped = true;
attack_Timer += Time.deltaTime;
if (attack_Timer > wait_Before_Attack)
{
enemy_Anim.Attack();
attack_Timer = 0f;
// play attack sound
// enemy_Audio.Play_AttackSound();
}
if (Vector3.Distance(transform.position, target.position) > attack_Distance + chase_After_Attack_Distance)
{
enemy_State = EnemyState.CHASE;
}
} // attack
void SetNewRandomDestination()
{
float rand_Radius = Random.Range(patrol_Radius_Min, patrol_Radius_Max);
Vector3 randDir = Random.insideUnitSphere * rand_Radius;
randDir += transform.position;
NavMeshHit navHit;
NavMesh.SamplePosition(randDir, out navHit, rand_Radius, -1);
navAgent.SetDestination(navHit.position);
}
void Turn_On_AttackPoint()
{
attack_Point.SetActive(true);
}
void Turn_Off_AttackPoint()
{
if (attack_Point.activeInHierarchy)
{
attack_Point.SetActive(false);
}
}
public EnemyState Enemy_State
{
get; set;
}
} // class
I would appreciate very it if someone could help with such an issue!
EDIT: I forgot to add the grass settings, these are as follows. As you can see there are no colliders.
I am digging some more and apparently the only walkable area is as follows (not entire map), how can I adjust this?
Below is how I did:
Painted the terrain with all kinds of grasses I needed and trees.
Undone all the painted grasses and trees.
Baked the navigation mesh(Navmesh) onto the terrain.
Redone all the painted grasses and trees.
Boom! Work done. :)
Why Do grasses not walkable?
Grasses have been painted like trees hence they are carved during baking process as trees.
Trick:
You have to paint the grasses and all the trees needed, then you have to unpaint all the grasses exceptional for the trees. After that bake the terrain, and undone the process(pressing CTRL + Z several times) until you see the grasses repainted.

Moving Player Up by holding left mouse button /space Microsoft VIsual Studio (Unity)

I'm not so good with Visual Studio.
I'm making a simple game and my gameobject (player) should move up when Space or Left Mouse Button is pressed.
Here is my code
using UnityEngine;
using System.Collections;
public class PixelMovement : MonoBehaviour {
Vector3 velocity = Vector3.zero;
public Vector3 PressVelocity;
public float maxSpeed = 5f;
public float fowardSpeed = 1f;
bool didPress = false;
// Use this for initialization
void Start () {
}
//Do Graphic & Input updates
void update() {
if(Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0)) {
didPress = true;
}
}
//Do physics engine updates here
void FixedUpdate () {
velocity.x = fowardSpeed;
if (didPress == true){
didPress = false;
velocity += PressVelocity;
}
velocity = Vector3.ClampMagnitude(velocity, maxSpeed);
transform.position += velocity * Time.deltaTime;
}
}
So, it should move like contrary to gravity. And when it stops holding, it continues to fall. I already have gravity I just need that "Up movement"
//Do Graphic & Input updates
void update() {
if(Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0)) {
didPress = true;
}
}
I think the problem is because update() should be Update()
Try:
//Do Graphic & Input updates
void Update() {
if(Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0)) {
didPress = true;
}
}
This is a quick fix: You're calling Input.GetKeyDown() and Input.GetMouseButtonDown() which only return true on the first frame that the button is pressed.
If you want a repeating event (I.E., the mouse button or space is held down), use Input.GetKey(KeyCode.Space) and Input.GetMouseButton(0).

Categories