Changing a game objects velocity on button press in unity - c#

So I'm trying to add a dash mechanic to a game character im building. However for some reason i can't get the game objects velocity to actually change. I tried using addForce which worked, but i had to add a lot in order to get the desired effect and that behaved strangely sometimes!
Do i need to do anything else to the game objects velocity than i already doing?
Heres my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float dashSpeed;
private int dashDirection;
private float dashCoolDown;
public float startDashCoolDown;
private float dashTime;
public float startDashTime;
public GameObject dashEffect;
public float speed;
public float jumpForce;
private float moveInput;
private Rigidbody2D rb;
private bool isFacingRight = true;
private Animator anim;
private bool isGrounded;
public Transform groundCheck;
public float checkRadius;
public LayerMask whatIsGround;
private int extraJumps;
public int extraJumpsValue;
public GameObject dustEffect;
public GameObject trailEffect;
private void Awake()
{
// Setting up references.
isGrounded = transform.Find("GroundCheck");
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
}
void Start()
{
extraJumps = extraJumpsValue;
rb = GetComponent<Rigidbody2D>();
dashTime = startDashTime;
dashCoolDown = startDashCoolDown;
}
void FixedUpdate()
{
isGrounded = false;
// Check to see if grounded
Collider2D[] colliders = Physics2D.OverlapCircleAll(groundCheck.position, checkRadius, whatIsGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
{
isGrounded = true;
anim.SetBool("Ground", isGrounded);
}
}
// Check if movement is allowed
if (!GameMaster.disableMovement)
{
// Move character
moveInput = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
Instantiate(trailEffect, groundCheck.position, Quaternion.identity);
anim.SetFloat("Speed", Mathf.Abs(moveInput));
}
// Flip character
if (isFacingRight == false && moveInput > 0)
{
Flip();
}
else if (isFacingRight == true && moveInput < 0)
{
Flip();
}
}
private void Update()
{
// Check if the player is grounded
if (isGrounded == true)
{
extraJumps = extraJumpsValue;
}
// Check if movement is allowed
if (!GameMaster.disableMovement)
{
// Check for jump
// If the player has more than one jump available
if (Input.GetKeyDown(KeyCode.Space) && extraJumps > 0)
{
isGrounded = false;
anim.SetBool("Ground", isGrounded);
rb.velocity = Vector2.up * jumpForce;
extraJumps--;
Instantiate(dustEffect, groundCheck.position, Quaternion.identity);
}
// If the player only has one jump available
if (Input.GetKeyDown(KeyCode.Space) && extraJumps == 0 && isGrounded == true)
{
isGrounded = false;
anim.SetBool("Ground", isGrounded);
rb.velocity = Vector2.up * jumpForce;
}
// Check for dash
if (dashCoolDown <= 0)
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
anim.SetBool("Dash", true);
Dash();
dashTime = startDashTime;
}
}
else
{
dashCoolDown -= Time.deltaTime;
}
}
}
void Dash()
{
if (dashTime <= 0)
{
dashCoolDown = startDashCoolDown;
anim.SetBool("Dash", false);
}
else
{
dashTime -= Time.deltaTime;
if (isFacingRight)
{
rb.velocity = Vector2.right * dashSpeed;
}
else if (!isFacingRight)
{
rb.velocity = Vector2.left * dashSpeed;
}
}
}
void Flip()
{
isFacingRight = !isFacingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}

If you dont get the desired dash effect with Rigidbody.velocity, you can try using Rigidbody.addForce(). I know you said you already used it, but there are multiple different force modes you can apply here. I would suggest using this one, because it applies full force from the start and then drops it off. You can read more about it yourself here.
So you could modify your code like so:
void Dash()
{
if (isFacingRight)
{
rb.AddForce(Vector2.right*dashSpeed, ForceMode.VelocityChange);
}
else if (!isFacingRight)
{
rb.AddForce(Vector2.left*dashSpeed, ForceMode.VelocityChange);
}
}
Note, that you also dont need to call dash repeatedly to falloff the velocity. this function should now be only called onse the button to dash (shift) has been pressed.
Hope this helped!

Related

Unity3D go down on slopes with a animated character

I'm developping a 3D game Unity with a squirrel as the player.
I'm struggling with a problem of slopes. I know, there are a bunch of tutorial to go down a slope whithout 'floating in the air while walking' but I didn't find a fine solution. I think it's because of the horizontal animations of the squirrel (maybe). I have tried with addForce, with a modified speed, with gravity... (maybe I implemented it wrong). I know I can check if I'm in the air or not with CharacterController.isGrounded but I can't force the squirrel to stick on the slope while running or walking. I'm sorry by advance if my question is too vague or simple.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
public class Squirrel : MonoBehaviour {
Animator squirrel;
public float gravity = 1.0f;
private Vector3 moveDirection = Vector3.zero;
float axisH, axisV;
public static int munitions = 0;
Rigidbody rb;
[SerializeField]
float walkSpeed = 2f, runSpeed = 8f, rotSpeed = 100f, jumpForce = 350;
private bool isJumpKeyDown = false;
[SerializeField] bool isJumping = false;
Animator characterAnimator;
int JumpCount = 0;
public int MaxJumps = 1; //Maximum amount of jumps (i.e. 2 for double jumps)
[SerializeField] GameObject nb_munitions;
CharacterController characterController;
// Use this for initialization
void Start () {
munitions = 0;
squirrel = GetComponent<Animator>();
rb = GetComponentInChildren<Rigidbody>();
characterAnimator = GetComponent<Animator>();
JumpCount = MaxJumps;
characterController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
GetInput();
nb_munitions.GetComponent<Text>().text = "Glands : " + munitions; //Affichage du score
Move();
}
private void FixedUpdate()
{
if (isJumpKeyDown)
{
squirrel.SetTrigger("jump");
JumpCount -= 1;
isJumpKeyDown = false;
}
}
public void GetInput()
{
axisV = Input.GetAxis("Vertical");
axisH = Input.GetAxis("Horizontal");
}
private void Move()
{
if (characterController.isGrounded)
{
//On the ground
}
else
{
//on the air
}
if (axisV > 0)
{
if (Input.GetKeyDown(KeyCode.LeftControl))
{
transform.position += Vector3.forward * walkSpeed * Time.deltaTime;
squirrel.SetBool("walk", true);
}
else
{
transform.position += Vector3.forward * runSpeed * Time.deltaTime;
squirrel.SetFloat("run", axisV);
squirrel.SetBool("walk", false);
}
}
else
{
squirrel.SetFloat("run", 0);
}
if (axisH != 0 && axisV == 0)
{
squirrel.SetFloat("h", axisH);
}
else
{
squirrel.SetFloat("h", 0);
}
if (axisH != 0)
{
transform.Rotate(Vector3.up * rotSpeed * Time.deltaTime * axisH);
}
if (Input.GetKeyDown(KeyCode.Space))
{
if (JumpCount > 0)
{
isJumpKeyDown = true;
}
}
//Call munitions
if (Input.GetKeyDown(KeyCode.LeftShift))
{
if (Squirrel.munitions > 0)
{
SpawnerScript.Instance.NewSpawnRequest();
munitions--;
}
}
}
}
You can try to get the angle of the slope and make it the pitch for the mesh of the squirrel.
I finally found the problem. My C# script "overwrited" the CharacterController and did not allow the squirrel to go down the slopes. Make sure you follow a move script that "respects" the CharacterController (if you pick one or you'll be fighting windmills).

Why does my dash only function properly if you aren't moving?

Here is the complete player controller file.
using UnityEngine;
public class PlayerCont : MonoBehaviour
{
[Header("Movement Variables")]
public float moveSpeed;
private float speed;
public float maxSpeed;
public float acceleration;
public float dropSpeed;
public float slideSpeed;
public int direction = 1;
[Header("Jump Variables")]
public float jumpForce;
public int extraJumps;
private float jumpTimeCounter;
public float jumpTime;
private bool isJumping;
private int jumpNum;
[Header("Dash Variables")]
public float dashSpeed;
public float dashLength = .5f;
public float dashCooldown = 1f;
private float dashCounter;
public float dashCoolCounter;
private KeyCode _lastKeyCode;
private float doubleTapTime = 0.05f;
private bool doubleTap;
public bool isDashing;
public float dashTime;
public float maxDashTime;
[Header("GroundCheck Variables")]
public Transform groundCheck;
public float checkRadius;
public LayerMask whatIsGround;
[Header("Debug Variables")]
public Rigidbody2D rb;
public float moveInputX;
public float moveInputY;
public bool facingRight = true;
public bool isGrounded;
public bool downKey;
public float rbxVel;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
speed = moveSpeed;
jumpNum = extraJumps;
}
void FixedUpdate()
{
}
// Update is called once per frame
void Update()
{
moveInputX = Input.GetAxisRaw("Horizontal");
moveInputY = Input.GetAxisRaw("Vertical");
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);
KeyChecks();
Jump();
GroundPound();
Move();
Dash();
}
void KeyChecks()
{
//restricts movement in Y to only be downward
if (moveInputY > 0)
{
moveInputY = 0;
}
//checks for player drop
if (!isGrounded && moveInputY < 0)
{
downKey = true;
}
else
{
downKey = false;
}
//changes direction relative to keypress
if (Input.GetKeyDown(KeyCode.A))
{
direction = -1;
}
if (Input.GetKeyDown(KeyCode.D))
{
direction = 1;
}
}
void Jump()
{
//sets jump number to user specified amount after touching ground
if (isGrounded)
{
extraJumps = jumpNum;
}
//jumps and decrements extrajumps by 1
if (Input.GetKeyDown(KeyCode.Space) && !downKey && extraJumps > 0)
{
isJumping = true;
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
extraJumps--;
}
//basic jump off of ground
else if (Input.GetKeyDown(KeyCode.Space) && extraJumps == 0 && isGrounded && !downKey)
{
isJumping = true;
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
//checks for longkeypress of spacebar and increases length of jump
if (Input.GetKey(KeyCode.Space) && extraJumps > 1 && isJumping) // allows a hold down increase to jump while grounded
{
if (jumpTimeCounter > 0)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
jumpTimeCounter -= Time.deltaTime;
}
else
{
jumpTimeCounter = jumpTime;
isJumping = false;
}
}
}
void GroundPound()
{
//ground pound keypress check
if (!isGrounded && Input.GetKeyDown(KeyCode.S))
{
if (!doubleTap && doubleTapTime > Time.time && _lastKeyCode == KeyCode.S)
{
rb.velocity = new Vector2(rb.velocity.x, -1 * dropSpeed);
Debug.Log("dashing right");
}
else
{
doubleTapTime = Time.time + 0.5f;
}
_lastKeyCode = KeyCode.S;
}
}
void Move()
{
//changes movement relative to input
if (!isDashing)
{
if (isGrounded && Input.GetKey(KeyCode.S))
{
rb.velocity = new Vector2(rb.velocity.x * .999f, rb.velocity.y);
}
else if (moveInputX == 0 && isGrounded)
{
speed = moveSpeed;
rb.velocity = new Vector2(rb.velocity.x * .99f, rb.velocity.y);
}
else if (moveInputX == 0 && !isGrounded)
{
speed = moveSpeed;
}
else
{
rb.velocity = new Vector2(moveInputX * speed, moveInputY / 10 + rb.velocity.y);
}
}
//checks player velocity
rbxVel = rb.velocity.x;
//increases speed relative to input direction
if (moveInputX > 0 || moveInputX < 0)
{
speed += acceleration;
}
//caps speed
if (speed > maxSpeed)
{
speed = maxSpeed;
}
//caps min speed
if (speed < moveSpeed)
{
speed = moveSpeed;
}
}
void Dash()
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
isDashing = true;
if (isDashing && dashCoolCounter <= 0)
{
dashTime -= Time.deltaTime;
dashCoolCounter = dashCooldown;
rb.velocity = new Vector2(dashSpeed * direction, rb.velocity.y);
Debug.Log("Dash Started");
}
}
else
{
dashTime = maxDashTime;
isDashing = false;
Debug.Log("No Dash");
}
//resets dash cooldown
if (dashCoolCounter > 0)
{
dashCoolCounter -= Time.deltaTime;
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
}
When using the keys for movement (A, S) the dash doesn't function. Oddly enough the code is executing (I see my debug statement in console) but nothing physically changes.
When rewriting the code for the dash from: rb.velocity = new Vector2(dashSpeed * direction, rb.velocity.y) to: rb.velocity = dashspeed the dash will work without issue. The only downside to that is that the Y component of the RigidBody is being manipulated as well.
This has been an issue for days now, and I am just rewriting the post.
Any and all help is welcomed.
You're setting isDashing = false too soon. It gets set to false as soon as you let go of Shift which allows Move to execute its code and change your rigidbody's velocity back to normal move.
Didn't test this, but give it a shot and see if it works the way you want it to.
void Dash()
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
if (!isDashing && dashCoolCounter <= 0)
{
isDashing = true;
dashTime = 0;
dashCoolCounter = dashCooldown;
rb.velocity = new Vector2(dashSpeed * direction, rb.velocity.y);
Debug.Log("Dash Started");
}
else if(isDashing)
{
rb.velocity = new Vector2(dashSpeed * direction, rb.velocity.y);
dashTime += Time.deltaTime;
if(dashTime >= maxDashTime)
{
isDashing = false;
Debug.Log("No Dash");
}
}
}
// resets dash cooldown
if (dashCoolCounter > 0)
{
dashCoolCounter -= Time.deltaTime;
}
}

Unity new Input-System and double jumping local multiplayer

So I have some trouble using the new Input System on a game I'm currently working on.
The game is going to be some type of an Smash game and I already had implemented double jump with the old Input System and it worked but now I've changed it to the new one and I can just jump one time in Air again I know it must be some kind of an easy fix problem but im a beginner and I don't really understand the new I- System. Here's my Code:
I would really appreciate if you could help me out with this and eventually I can learn something of ur comment. (Btw. sorry for my english I'm not native lol)
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
public float speed;
public float jumpForce;
public float moveInput;
public float checkRadius;
private int extraJumps;
public int extraJumpsValue;
private Rigidbody2D rb;
private bool facingRight = true;
private bool isGrounded;
public Transform groundCheck;
public LayerMask whatIsGround;
private Vector2 movementInput = Vector2.zero;
private bool jumped = false;
//OnMove Input to later set as Event in Input Manager
public void OnMove(InputAction.CallbackContext context)
{
movementInput = context.ReadValue<Vector2>();
}
//OnJump Input to later set as Event in Input Manager
public void OnJump(InputAction.CallbackContext context)
{
jumped = context.action.triggered;
}
//start
private void Start()
{
extraJumps = extraJumpsValue;
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
//check if isGrounded
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius,
whatIsGround);
moveInput = movementInput.x;
//Move Right/Left relative to moveInput Value (-1 till 1)
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
//rotate Player Sprite relative to a / d Input
if(facingRight == false && moveInput > 0)
{
Flip();
}
else if(facingRight == true && moveInput <0)
{
Flip();
}
}
private void Update()
{
// if grounded set extra jumps u can take to a preset value
if(isGrounded == true)
{
extraJumps = extraJumpsValue;
}
//if extrajumps is equal to 0 & player tries to jump and is grounded add upwards velocity
if (extraJumps == 0 && jumped && isGrounded == true)
{
rb.velocity = Vector2.up * jumpForce;
}
//subtract extra jump -1 and "jump"
else if (extraJumps > 0 && jumped)
{
rb.velocity = Vector2.up * jumpForce;
extraJumps--;
}
}
//rotate player
void Flip()
{
facingRight = !facingRight;
transform.Rotate(0f, 180f, 0f);
}
}
I think the problem is in the condition to execute the first jump :
//When isGrouded then extraJumps equal 1 (in the case extraJumpsValue is 1)
if(isGrounded == true)
{
extraJumps = 1;
}
//The next condition is always false
//Because when isGrouded then extraJumps is never 0
if (isGrounded == true && extraJumps == 0 && /*Some other condition*/)
...
I don't untertand why extraJumps is checked to do the first jump. I think you can remove this operand :
if (/*extraJumps == 0 &&*/ jumped && isGrounded == true)
{
rb.velocity = Vector2.up * jumpForce;
}
Full code :
private void Update()
{
// if grounded set extra jumps u can take to a preset value
if(isGrounded == true)
{
extraJumps = extraJumpsValue;
}
//if player tries to jump and is grounded add upwards velocity
if (jumped && isGrounded == true)
{
rb.velocity = Vector2.up * jumpForce;
}
//subtract extra jump -1 and "jump"
else if (extraJumps > 0 && jumped)
{
rb.velocity = Vector2.up * jumpForce;
extraJumps--;
}
}

Unity 2D: How to make patrolling AI turn around?

I'm making a 2D platformer in Unity, and made a patrolling enemy with code from a tutorial video. The enemy basically moves randomly to different spots in the scene. But how can I make the sprite turn around?
This is my code so far. I've tried with different approaches, but not getting the expected behavior.
public float speed = 10f;
private float waitTime;
public float startWaitTime = 1f;
public Transform[] moveSpots;
private int randomSpot;
private bool moving = true;
private bool m_FacingRight = true;
void Start()
{
waitTime = startWaitTime;
randomSpot = Random.Range(0, moveSpots.Length);
}
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, moveSpots[randomSpot].position, speed * Time.deltaTime);
if (Vector2.Distance(transform.position, moveSpots[randomSpot].position) < 0.2f)
{
//Debug.Log(m_FacingRight);
// if (moving.x > 0 && !m_FacingRight)
// {
// Debug.Log("moving right");
// Flip();
// }
// else if (moving.x < 0 && m_FacingRight)
// {
// Debug.Log("moving left");
// Flip();
// }
if (waitTime <= 0)
{
//moving = true;
randomSpot = Random.Range(0, moveSpots.Length);
waitTime = startWaitTime;
}
else
{
//moving = false;
waitTime -= Time.deltaTime;
}
}
}
//private void Flip()
//{
//m_FacingRight = !m_FacingRight;
//transform.Rotate(0f, 180f, 0f);
//}
**********************************EDIT****************************************
I ended up with this for the enemy script movement
private bool facingRight = true;
private Rigidbody2D rigidBody2D;
private SpriteRenderer spriteRenderer;
public Vector2 speed = new Vector2(10, 0);
public Vector2 direction = new Vector2(1, 0);
private void Awake()
{
rigidBody2D = GetComponent<Rigidbody2D>();
spriteRenderer = GetComponent<SpriteRenderer>();
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.CompareTag("Wall") || collision.collider.CompareTag("Player"))
{
direction = Vector2.Scale(direction, new Vector2(-1, 0));
}
if (!collision.collider.CompareTag("Ground"))
{
if (!facingRight)
{
Flip();
}
else if (facingRight)
{
Flip();
}
}
}
void FixedUpdate()
{
Vector2 movement = new Vector2(speed.x * direction.x, 0);
movement *= Time.deltaTime;
transform.Translate(movement);
}
private void Flip()
{
facingRight = !facingRight;
if (!facingRight)
{
spriteRenderer.flipX = true;
}
else if (facingRight)
{
spriteRenderer.flipX = false;
}
}
Rewrite your Flip function to
private void Flip()
{
m_FacingRight = !m_FacingRight;
GetComponent<SpriteRenderer>().flipX = true;
}
Also, if you're looking for a reference, I made a platformer in Unity that includes enemy patrolling https://github.com/sean244/Braid-Clone
In a sidescroller, an easy way to achieve this is to use SpriteRenderer.flipX.
For instance, if you want to flip X when the velocity is negative:
var sr = GetComponent<SpriteRenderer>();
sr.flipX = velocity.x < 0;

Unity Click on 1 object to trigger another object

Please keep in mind that I'm new to Unity. I have 2 script that I want to "combline" but when I try then it don't Work.
I have a Script (Name : RobotController). This script controls the movement of the player. Up/Jump, Down, Left and Right. (This Works with Keyboard keys only atm)
This script Works just fine but now I want to add the feature of touch keys for phone. With this I mean that if a person click on the "up-Arrow" the player shall jump.
The Up-Arrow is an object.
This is were I get my problem. I have created the Up-Arrow with a collider and a script.
Up-Arrow script:
public class NewJumpScript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnMouseOver()
{
if ((Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) || (Input.GetMouseButtonDown(0)))
{
Debug.Log("test");
}
}
}
Here is the RobotController script´, with ground check and so on.
public class RobotController : MonoBehaviour {
//This will be our maximum speed as we will always be multiplying by 1
public float maxSpeed = 2f;
public GameObject player;
public GameObject sprite;
//a boolean value to represent whether we are facing left or not
bool facingLeft = true;
//a value to represent our Animator
Animator anim;
//to check ground and to have a jumpforce we can change in the editor
bool grounded = true;
public Transform groundCheck;
public float groundRadius = 1f;
public LayerMask whatIsGround;
public float jumpForce = 300f;
private bool isOnGround = false;
void OnCollisionEnter2D(Collision2D collision) {
isOnGround = true;
}
void OnCollisionExit2D(Collision2D collision) {
anim.SetBool ("Ground", grounded);
anim.SetFloat ("vSpeed", rigidbody2D.velocity.y);
isOnGround = false;
}
// Use this for initialization
void Start () {
player = GameObject.Find("player");
//set anim to our animator
anim = GetComponent <Animator>();
}
void FixedUpdate () {
//set our vSpeed
//set our grounded bool
grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);
//set ground in our Animator to match grounded
anim.SetBool ("Ground", grounded);
float move = Input.GetAxis ("Horizontal");//Gives us of one if we are moving via the arrow keys
//move our Players rigidbody
rigidbody2D.velocity = new Vector3 (move * maxSpeed, rigidbody2D.velocity.y);
//set our speed
anim.SetFloat ("Speed",Mathf.Abs (move));
//if we are moving left but not facing left flip, and vice versa
if (move > 0 && !facingLeft) {
Flip ();
} else if (move < 0 && facingLeft) {
Flip ();
}
}
void Update(){
if ((isOnGround == true && Input.GetKeyDown (KeyCode.UpArrow)) || (isOnGround == true && Input.GetKeyDown (KeyCode.Space))) {
anim.SetBool("Ground",false);
rigidbody2D.AddForce (new Vector2 (0, jumpForce));
}
if (isOnGround == true && Input.GetKeyDown (KeyCode.DownArrow))
{
gameObject.transform.localScale = new Vector3(transform.localScale.x, 0.2f, 0.2f);
}
if (isOnGround == true && Input.GetKeyUp (KeyCode.DownArrow))
{
gameObject.transform.localScale = new Vector3(transform.localScale.x, 0.3f, 0.3f);
}
}
//flip if needed
void Flip(){
facingLeft = !facingLeft;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
What needs to happen is that when The "Up-arrow" in the game is clicked then The person shall jump on the same tearms as in the RobotController script.
I hope you understand my question.
Thanks for your time and help.
I posted this same answer to both of the questions, because they are so similar. You can easily modify the code to your needs.
This is only one way to do it. There are probably many more, but this is the best I have encountered so far.
On the QUI button, script like this is needed:
private Mover playerMover;
void Start()
{
playerMover = GameObject.Find("Character").GetComponent<Mover>();
}
void OnMouseOver()
{
if (Input.GetMouseButton(0))
{
Debug.Log("pressed");
playerMover.MoveButtonPressed();
}
}
Notice that find is only done ones in start function, because it is computationally heavy.
And on the Character gameobject, script component like this is needed:
using UnityEngine;
using System.Collections;
public class Mover : MonoBehaviour {
public void MoveButtonPressed()
{
lastPressedTime = Time.timeSinceLevelLoad;
}
public double moveTime = 0.1;
private double lastPressedTime = 0.0;
void Update()
{
if(lastPressedTime + moveTime > Time.timeSinceLevelLoad)
{
// Character is moving
rigidbody.velocity = new Vector3(1.0f, 0.0f, 0.0f);
}
else
{
rigidbody.velocity = new Vector3(0.0f, 0.0f, 0.0f);
}
}
}

Categories