- Home /
Collision on Key press
Im using a scene with a 3rd person controller character and a sphere meant as a football, my objective is to add force to the sphere when I press the RightShift key, I cant get it to work.
Here´s what my script looks like:
using UnityEngine;
using System.Collections;
public class strike : MonoBehaviour
{
public int speed = 1000;
void TryHit()
{
if(Input.GetKeyDown(KeyCode.RightShift))
GetComponent<Rigidbody>().AddForce(transform.forward * speed);
}
}
Thanks in advance!
Answer by aditya007 · Dec 20, 2016 at 09:57 AM
You defined the Input condition inside function TryHit which may or may not be called. More importantly, it will be next to impossible to get the input just when the TryHit is called.
What you want to do is Put that code inside the Update() function, which is called every frame. Here you can continuously check whether there was a key press or not.
using UnityEngine;
using System.Collections;
public class strike : MonoBehaviour
{
public int speed = 1000;
void Update()
{
if(Input.GetKeyDown(KeyCode.RightShift))
GetComponent<Rigidbody>().AddForce(transform.forward * speed);
}
}
Answer by $$anonymous$$ · Dec 20, 2016 at 03:25 PM
One of your reasons could be that the TryHit() method is never being called. Another reason could be that the game object does not have a Rigidbody attached to it.
Your answer
Follow this Question
Related Questions
Script appears as null and not null at the same time 1 Answer
Player getting stuck in corners 0 Answers
Weird Collisions Between Paddle and Ball (Breakout) 0 Answers
My trigger is called twice 1 Answer
Collisions, but on 100,000 cubes? 1 Answer