I have a button for which i'd like to signify "attacking". I'm programming for android.
Basically i'd like to run this script, upon the touch of the attack button. Instead of using the F key to stop the code from rapidly repeating, i'm trying to figure out how to run an if statement for "if button is touched & !isAttacking" then go into the method.
if (Input.GetKeyDown(KeyCode.F) && !isAttacking)
{
isAttacking = true;
attackTimer = attackCD;
Debug.Log("F Pressed");
attackTrigger.enabled = true;
}
if (isAttacking)
{
if (attackTimer > 0)
{
attackTimer -= Time.deltaTime;
}
else
{
isAttacking = false;
attackTrigger.enabled = false;
}
}
I'm using Unity 5!
Related
I am trying to convert my PC game code in unity to android and I am stuck on the controls change. Please help!
This is the code:
Getting the state of rocket.
enum State { Dying, Alive, Transcending }
State state = State.Alive;
// Update is called once per frame
void Update()
{
if (state == State.Alive)
{
RespondToThrustInput();
RespondToRotateInput();
}
}
When the rocket collides with anything it checks whether it's friendly or not before changing its state from alive to dead.
private void OnCollisionEnter(Collision collision)
{
if (state != State.Alive) { return; }
switch (collision.gameObject.tag)
{
case "Friendly":
break;
case "Finish":
state = State.Transcending;
audioSource.Stop();
audioSource.PlayOneShot(finishgame);
finishgameParticles.Play();
Invoke("LoadNextScene", levelloaddelay);
break;
default:
state = State.Dying;
audioSource.Stop();
audioSource.PlayOneShot(death);
deathParticles.Play();
Invoke("LoadFirstScene", levelloaddelay);
break;
}
}
private void LoadFirstScene()
{
SceneManager.LoadScene(9);
}
Loading next scene using build index.
private void LoadNextScene()
{
if (nextscenetoload > 7)
{
nextscenetoload = 0;
}
SceneManager.LoadScene(nextscenetoload);
}
Space for ignition or force and audio sources for playing sound effects.
private void RespondToThrustInput()
{
if (Input.GetKey(KeyCode.Space))
{
ApplyThrust();
}
else
{
audioSource.Stop();
mainengineParticles.Stop();
}
}
Apply thrust is the method I wrote with the logic of the rocket thrust.
private void ApplyThrust()
{
rigidbody.AddRelativeForce(Vector3.up * mainThrust * Time.deltaTime);
if (!audioSource.isPlaying)
audioSource.PlayOneShot(mainengine);
mainengineParticles.Play();
}
Rotation of the rocket or Left and right. Here I am trying to rotate the rocket using the A and D keys
void RespondToRotateInput()
{
float rotationThisFrame = rcsThrust * Time.deltaTime;
if (Input.GetKey(KeyCode.A))
{
rigidbody.freezeRotation = true;
transform.Rotate(Vector3.forward * rotationThisFrame);
rigidbody.freezeRotation = false;
}
else if (Input.GetKey(KeyCode.D))
{
rigidbody.freezeRotation = true;
transform.Rotate(-Vector3.forward * rotationThisFrame);
rigidbody.freezeRotation = false;
}
}
For PC games there is a keyboard to use to control, but for the android there are touches, you have to verify if there is a touch on the screen, like this:
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
//do something
}
also you need more work to determine where the touch is located and do you customizations... or in case you're not interested about this input handling, you can use some assets from Unity Assets Store to cover this part for you.
check this link for more information about touch control in Unity documentation:
https://docs.unity3d.com/ScriptReference/Input.GetTouch.html
I want to check that Rectangle was tapped. This mehod does the job and it works almost how I want:
private bool CheckRectangleTouch(Rectangle target)
{
var touchCollection = TouchPanel.GetState();
if (touchCollection.Count > 0)
{
foreach (var touch in touchCollection)
{
if (target.Contains(touch.Position))
{
return true;
}
}
}
return false;
}
Problem I have is that after I've tapped rectangle it keeps returning true until I release it (it can register 10-30 times for one tap) and I want it to return true just once - for the first touch.
I've tried this (replace code inside foreach):
var isFirstTouch = !touch.TryGetPreviousLocation(out _);
if (target.Contains(touch.Position) && isFirstTouch)
{
return true;
}
And this (bad one, I don't really want it to register after release):
if (target.Contains(touch.Position) && touch.State == TouchLocationState.Released)
{
return true;
}
But nothing is does it. Either logic is not consistent or doesn't work at all.
So how do I check for tap?
Update: this works but it's very hacky, has delay and gives me random phantom taps:
try
{
var tap = TouchPanel.ReadGesture(); // falls each time when no input
return tap.GestureType == GestureType.Tap && target.Contains(tap.Position);
}
catch { }
return false;
Here's what I ended up doing:
I have singleton to hold my game state (many different props updated as needed). I added to it:
public TouchCollection TouchCollection { get; set; }
Prop to hold TouchPanel.GetState result. I fill it in Games Update method once per frame, as #craftworkgames suggested:
State.TouchCollection = TouchPanel.GetState();
Also I added this prop to my game state:
public bool TouchActive { get; set; }
And this is the method to check for rectangle tap. It returns true only for the first contact in tap:
private bool CheckRectangleTap(Rectangle target)
{
if (State.TouchCollection.Count == 0)
{ // if no input
return State.TouchActive = false;
}
var targetTouched = false;
foreach (var touch in State.TouchCollection)
{
if (target.Contains(touch.Position))
{
targetTouched = true;
}
}
if (targetTouched && !State.TouchActive)
{ // if target is touched and it's first contact
return State.TouchActive = true;
}
return false;
}
It doesn't seem ideal but it works for my case.
I have been trying to built an app based on GHOST game.
I have written an onKeyUp function which only accepts lowercase alphabets and adds it to a string called wordfragment and then calling the function computerTurn in it. But i had seen after successfully running first time i.e. calling the computerTurn function and getting return statement from computerturn function it(onkeyup) does not works second time.
Here my code to onKeyUp function.
#Override
public boolean onKeyUp(int KeyCode, KeyEvent event) {
char ch = (char)event.getUnicodeChar();
if( !( ch >= 'a' && ch <='z' ) ) {
return super.onKeyUp(KeyCode, event);
}
wordFragment = wordFragment + ch;
label.setText(COMPUTER_TURN);
text.setText(wordFragment);
userTurn = false;
computerTurn();
return true;
}
and my code to computerTurn function is
private boolean computerTurn() {
if(wordFragment.length() >= 4 && dictionary.isWord(wordFragment)){
label.setText("Computer wins");
// challenge.setEnabled(false);
return true;
}
else {
String word = dictionary.getAnyWordStartingWith(wordFragment.toLowerCase());
if(word!=null){
Toast.makeText(GhostActivity.this, "comp word found", Toast.LENGTH_SHORT).show();
wordFragment += word.charAt(wordFragment.length());
}
else{
Toast.makeText(GhostActivity.this, "comp word not found", Toast.LENGTH_SHORT).show();
label.setText("User Wins!!");
//challenge.setEnabled(false);
// wordFragment += (char)(random.nextInt(26) + 61);
}
}
// Do computer turn stuff then make it the user's turn again
userTurn = true;
label.setText(USER_TURN);
text.setText(wordFragment);
Toast.makeText(GhostActivity.this, "return true", Toast.LENGTH_SHORT).show();
return true;
}
Android softkeyboards rarely use key events. The correct way to use an android soft keyboard is via InputConnection. Only hardware keys generally issue key events. Basically you're coding this the right way for Windows or web, but the wrong way for Android.
Reference:Change go button to next button in android
I am developing an application with sign up page using Ionic framework.
Is there any option to replace go button with next button? I want to move cursor from one field to another using next button in the keyboard.
you can use following reference to achieve your requirement in ionic.Below code is for cordova
(function($) {
$.fn.enterAsTab = function(options) {
var settings = $.extend({
'allowSubmit': false
}, options);
this.find('input, select, textarea, button').live("keypress", {localSettings: settings}, function(event) {
if (settings.allowSubmit) {
var type = $(this).attr("type");
if (type == "submit") {
return true;
}
}
if (event.keyCode == 13) {
var inputs = $(this).parents("form").eq(0).find(":input:visible:not(disabled):not([readonly])");
var idx = inputs.index(this);
if (idx == inputs.length - 1) {
idx = -1;
} else {
inputs[idx + 1].focus(); // handles submit buttons
}
try {
inputs[idx + 1].select();
}
catch (err) {
// handle objects not offering select
}
return false;
}
});
return this;
};
})(jQuery);
For adding next button , you can refer following link:
How to add Next button in Ionic soft keyboard plugin
I'm developing an app using Flash CC. I'm using the Google Play Services to login the people in the App, but I have a problem.
When I install the App, I have to login. When I'm logged in, I don't have problems. If I close the app and then I open again the game, says that I'm not logged in. So, I click login, I log in but then I recive the SIGN_IN_FAILS error. In the code, first I check if the user is logged in and if is not logged in, I show the Log In button. But what happens with the people who has connected before? I have an "else" telling that if he is already logged in, he can 'Continue'. But always says that I'm not logged and I have to log in! But if I log in another time I get the error!
PS. I'm using freshplanet/laurentiu ANE/library.
** EDIT **
CODE:
import com.freshplanet.ane.AirGooglePlayGames.AirGooglePlayGames;
import com.freshplanet.ane.AirGooglePlayGames.AirGooglePlayGamesEvent;
import com.laurentiu.ane.AirGooglePlayServices.AirGooglePlayServices;
var airGooglePlayGames: AirGooglePlayGames = AirGooglePlayGames.getInstance();
airGooglePlayGames.addEventListener(AirGooglePlayGamesEvent.ON_SIGN_IN_SUCCESS, onSignInSuccess);
airGooglePlayGames.addEventListener(AirGooglePlayGamesEvent.ON_SIGN_OUT_SUCCESS, onSignOutSuccess);
airGooglePlayGames.addEventListener(AirGooglePlayGamesEvent.ON_SIGN_IN_FAIL, onSignInFail);
this.checkeStatus();
button_login.addEventListener(MouseEvent.CLICK, googleSignIn);
btn_out.addEventListener(MouseEvent.CLICK, googleSignOut);
btn_out.visible = false;
button_login.visible = false;
function googleSignIn(e: MouseEvent = null): void {
AirGooglePlayGames.getInstance().signIn();
}
function checkeStatus() {
if (!AirGooglePlayGames.getInstance().isSignedIn()) {
// Always stay here when I reopen the app
btn_out.visible = false;
button_login.visible = true;
} else {
// I never arrive here
texto.text = "PLAYERID: " + AirGooglePlayGames.getInstance().getActivePlayerID();
loadingBar.gotoAndStop(2);
button_login.visible = false;
btn_out.visible = true;
}
}
function onSignInSuccess(e: AirGooglePlayGamesEvent): void {
// I only arrive here if is the first time I open the app and login for first time
texto.text = "PLAYERID: " + AirGooglePlayGames.getInstance().getActivePlayerID();
loadingBar.gotoAndStop(2);
button_login.visible = false;
btn_out.visible = true;
}
function onSignOutSuccess(e: AirGooglePlayGamesEvent): void {
texto.text = "SIGN OUT OKAY!";
loadingBar.gotoAndStop(1);
button_login.visible = true;
btn_out.visible = false;
}
function onSignInFail(e: AirGooglePlayGamesEvent): void {
texto.text = "SING IN FAIL: " + e;
loadingBar.gotoAndStop(1);
button_login.visible = true;
btn_out.visible = false;
}
function googleSignOut(e: AirGooglePlayGamesEvent): void {
texto.text = "SIGN OUT PROGRESS";
airGooglePlayGames.signOut();
loadingBar.gotoAndStop(1);
button_login.visible = true;
btn_out.visible = false;
}
Any idea what could happen?
A few things that might help:
I think your stuff at the top should be in a constructor function. For this type of code, with event listeners, you might be much better off making an external .as3 file and attach to a document class or movieClip base class, than putting the code in the timeline, as I think your code might not always be available as you move around??
And I notice you do:
this.checkeStatus();
Right away, which might do this:
btn_out.visible = false;
button_login.visible = true;
Or it might do this:
button_login.visible = false;
btn_out.visible = true;
But I think it doesn't matter because right after that, you return to the line under this.checkeStatus(), and get this:
btn_out.visible = false;
button_login.visible = false;
So no matter what happened with this.checkeStatus(), you end up with both buttons turned off, no? So maybe try moving this.checkeStatus(); down to the bottom of the constructor function so it goes last.
It might be more compact and less confusing to break off all these repeating visible = false / true lines into their own function like:
private function setStatusButtonsVisible(status:Boolean){
button_login.visible = status;
btn_out.visible = !status;
if (status){
loadingBar.gotoAndStop(2);
}else{
loadingBar.gotoAndStop(1);
}
}
Since in all cases but the first you're toggling the 2nd to be the opposite of the first.