I have a method that applies force to a ball in Box2d.
Testing it locally on desktop it works fine, but on iPad (ios7)
the method get executed only until the half!
I never came accross such a weird error, what is wrong here:
function onTouch(e:TouchEvent) {
var touch:Touch = e.getTouch(this) as Touch;
if (touch && touch.phase == TouchPhase.ENDED) {
//do something
_debugT.text = "works";
var mouseX_m:Number = touch.globalX;
var mouseY_m:Number = touch.globalY;
_debugT.text = "stops here...";
var xDiff:Number = mouseX_m - (_whiteBall.GetPosition().x * WORLD_SCALE);
var yDiff:Number = mouseY_m - (_whiteBall.GetPosition().y * WORLD_SCALE);
var angle:Number = Math.atan2(yDiff, xDiff);
var angleDeg:Number = angle * 180 / Math.PI;
_debugT.text = "never gets executed"
var len = Math.sqrt((xDiff * xDiff) + (yDiff * yDiff));
var vx = len * Math.cos(angle);
var vy = len * Math.sin(angle);
var vel = _whiteBall.GetLinearVelocity();
vel.x += (vx * 5);
vel.y += (vy * 5);
var force = new b2Vec2(vel.x, vel.y);
_whiteBall.SetAwake(vel);
_whiteBall.SetLinearVelocity(force);
}
}
To me it looks like Multitouch.inputMode = MultitouchInputMode.GESTURE; causes this problem.
I had the same issue and commented out this line and it works now.
Related
I am making a drag and drop activity where multiple items are to be placed at the same target. I have action code on the main time line and then code attached to a sprite.
Problems:
When I release the object if it is correct it should snap to the top of that section. If it is incorrect it should return to its original orientation to be picked up again. Unfortunately it stays where I placed it, and does not move back to original place when it is incorrect. I have fixed other issues with this flash file as to if code is supposed to be on the main time line or in the sprite, but this does not seem to have an effect after the object is released. Near the end of the script there is _root.rlamp1.gotoAndPlay(1) this is a buzzer that goes off if the answer is incorrect. This is working correctly.
I do not know if these are related Items but if the correct placement is given I want the next item to start in the original position, but it is starting where my mouse is instead of the original position. I am relatively new to coding and am trying to make an activity for my science class to get instant feedback to see if they understand to concept.
Thanks for your help.
// [Action in Frame 1]
answername = Array();
answerdest = Array();
answername[0] = "gravel";
answerdest[0] = "1";
answername[1] = "nuts and bolts";
answerdest[1] = "1";
answername[2] = "oxygen";
answerdest[2] = "2";
answername[3] = "helium";
answerdest[3] = "2";
answername[4] = "gold";
answerdest[4] = "2";
dbCount = 0;
dbutton.duplicateMovieClip("dbutton" + dbCount,dbCount * 100);
dbutton.visible = false;
dbutton0.answer = answerdest[dbCount];
dbutton0.theText.text = answername[dbCount];
// This code is on the sprite and not on the main actionscript
onClipEvent (load)
{
this.defx = _x;
this.defy = _y;
if (this.theText.text.length > 20)
{
this.theText._height = 31;
this.theBox._height = 27;
}
else
{
this.theText._height = 19;
this.theBox._height = 19;
} // end else if
}
on (press)
{
if (this.noDrag !=true)
{
startDrag (this,false);
}
}
on (release)
{
if (this.noDrag != true)
{
stopDrag ();
if(this.hitTest(_root["dz" + this.answer]))
{
totalHeight = 0;
for (v = 0; v < _root.dbCount; v++)
{
if (_root["dbutton" + v].answer == this.answer)
{
totalHeight = totalHeight + _root["button" + v].theBox._height ;
} // end if
} // end of for
++_root.dbCount;
this .duplicateMovieClip("dbutton" + _root.dbCount, _root.dbCount * 100);
_root["dbutton" + _root.dbCount]._x = this.defX;
_root["dbutton" + _root.dbCount]._y = this.defY;
_root["dbutton" + _root.dbCount].answer = _root.answerdest[_root.dbCount + 1];
_root["dbutton" + _root.dbCount].theText.text = _root.answername[_root.dbCount +1];
if (_root["dbutton" + _root.dbCount].theText.text == "undefined")
{
_root["dbutton" + _root.dbCount].theText.text = "Finished!";
_root["dbutton" + _root.dbCount].noDrag = true;
} // end if
this.noDrag = true;
this._y = _root["dz" + this.answer]._y + totalHeight;
this._x = _root["dz" + this.answer]._x - _root["dz" + this.answer]._width / 2;
++_root["dz" + this.answer].numItems;
_root.glamp1.gotoAndPlay (1);
}
else
{
this.X = this.defX;
this._Y = this.defY;
_root.rlamp1.gotoAndPlay(1);
} // end if
} // end else if
}
The problem is that there are misspelled variable names and properties in the sprite code.
Replace these lines
this.X = this.defX;
this._Y = this.defY;
with those lines
this._x = this.defx;
this._y = this.defy;
and your code should work.
I have some error related to IndexOutOfRangeException. The number of errors is over 200 and the error comes up when I play the game.
Error shown like this:
IndexOutOfRangeException: Array index is out of range. GameController.OnGUI () (at Assets/MicroRacers Assets/Scripts/GameController.js:67)
Here is the code of my game controller.
var CheckPoints:Transform[];
var LapsToWin:int = 5;
var PointsPerPlace:Array = new Array(8,4,2,1);
var CountDownToStart:float = 5;
var Items:Transform[];
var ItemCopy:Object;
var SpawnTime:Vector2 = Vector2(5,10);
private var SpawnTimeCount:float = 0;
var MaximumItems:int = 5;
private var ItemCount:int = 0;
private var FinishPlace:int = 0;
private var Players:int = 1;
var RaceEndDelay:float = 5;
//~ function Awake()
//~ {
//~ Application.targetFrameRate = 30;
//~ }
function Start()
{
SpawnTimeCount = Random.Range(SpawnTime.x, SpawnTime.y);
}
function Update ()
{
if ( SpawnTimeCount > 0 )
{
SpawnTimeCount -= Time.deltaTime;
}
else if ( ItemCount < MaximumItems )
{
SpawnTimeCount = Random.Range(SpawnTime.x, SpawnTime.y);
ItemCount++;
ItemCopy = Instantiate(Items[Mathf.Floor(Random.Range(0, Items.length - 1))], CheckPoints[Mathf.Floor(Random.Range(0, CheckPoints.length - 1))].position + Vector3.up * 0.3, Quaternion.identity);
ItemCopy.transform.Translate(Vector3.right * Random.Range(-3,3), Space.Self);
}
if ( Players == 0 )
{
RaceEndDelay -= Time.deltaTime;
if ( RaceEndDelay <= 0 )
{
Application.LoadLevel("end");
}
}
}
//This script displays the HUD, with current weapon, ammo left, Health, Shield, and score
var GUIskin:GUISkin; //The skin gui we'll use
var CountdownTextures:Texture2D[];
private var CountdownTextureIndex:int = 0;
function OnGUI()
{
GUI.skin = GUIskin; //The skin gui we'll use
if ( CountDownToStart > Time.timeSinceLevelLoad )
{
GUI.DrawTexture(Rect( (Screen.width - CountdownTextures[Mathf.Round(Time.timeSinceLevelLoad)].width) * 0.5, (Screen.height - CountdownTextures[Mathf.Round(Time.timeSinceLevelLoad)].height) * 0.5, CountdownTextures[Mathf.Round(Time.timeSinceLevelLoad)].width, CountdownTextures[Mathf.Round(Time.timeSinceLevelLoad)].height), CountdownTextures[Mathf.Round(Time.timeSinceLevelLoad)]); //Draw the HUD texture
}
}
Mathf.Round(Time.timeSinceLevelLoad) is just bigger CountdownTextures array size.
Maybe try adding this:
Debug.Log("Index: "+Mathf.Round(Time.timeSinceLevelLoad)+", Array size: "+ CountdownTextures.Length);
And you should see that index is bigger than size.
You can also add kind of safety check inside if, something like this:
if(Mathf.Round(Time.timeSinceLevelLoad) < CountdownTextures.Length && <your second statement>)
This is my script (written in JavaScript), which creates a camera movement. I can't figure out how to make it so that I can get it to not move too close to the object (target). It is probably something simple, but I'm a noob at Unity.
If it's not possible to get it by modifying the existing code, could you suggest another way to get the desired motion?
#pragma strict
var target : Transform;
var localOffset = Vector3(0,0,0);
var finalPos : Vector3;
var currentPos : Vector3;
var speed = 0.01;
private var startTime: float;
private var journeyLength: float;
function Start() {
startTime = Time.time;
}
function Update () {
currentPos = transform.position;
finalPos = target.position + (target.up * localOffset.z);
finalPos = target.position + (target.forward * localOffset.x);
transform.LookAt(target.position);
journeyLength = Vector3.Distance(transform.position, finalPos);
var distCovered = (Time.time - startTime) * speed;
var fracJourney = distCovered / journeyLength;
transform.position = Vector3.Lerp(transform.position, finalPos, fracJourney);
}
I would use Vector3.Distance
function Update()
{
...
if (Vector3.Distance(target.position, transform.position) > 10) // Change '10' to any distance that you want as a minimum
{
transform.position = Vector3.Lerp(transform.position, finalPos, fracJourney);
}
Hope this helps :)
There's a small bug in your code, if you replace:
finalPos = target.position + (target.up * localOffset.z);
finalPos = target.position + (target.forward * localOffset.x);
with:
finalPos = target.position + (target.up * localOffset.z);
finalPos += (target.forward * localOffset.x);
will you get what you want?
OVERALL GOAL: Have the camera change target to the selected car
I'm new to the unity game engine and got a bit of a problem.
So, I have a successful car selector which changes between cars and starts the match with that car. Everything there works. The only issue is that my "CarCameraScript" has a transform variable which is always 1 of the 3 cars. I want it to change dependant on the selected car.
Here is the look at the code of the CarCameraScript
#pragma strict
var car : Transform;
var distance: float = 6.4;
var height: float = 1.4;
var rotationDamping : float = 3.0;
var heightDamping: float = 2.0;
var zoomRatio : float = 0.5;
var DefaultFOV : float = 60;
private var rotationVector : Vector3;
function Start () {
}
function LateUpdate () {
var wantedAngel = rotationVector.y;
var wantedHeight = car.position.y + height;
var myAngel = transform.eulerAngles.y;
var myHeight = transform.position.y;
myAngel = Mathf.LerpAngle(myAngel,wantedAngel,rotationDamping*Time.deltaTime);
myHeight = Mathf.Lerp(myHeight,wantedHeight,heightDamping*Time.deltaTime);
var currentRotation = Quaternion.Euler(0,myAngel,0);
transform.position = car.position;
transform.position -= currentRotation*Vector3.forward*distance;
transform.position.y = myHeight;
transform.LookAt(car);
}
function FixedUpdate () {
var localVilocity = car.InverseTransformDirection(car.rigidbody.velocity);
if (localVilocity.z<-0.5) {
rotationVector.y = car.eulerAngles.y + 180;
} else {
rotationVector.y = car.eulerAngles.y;
}
var acc = car.rigidbody.velocity.magnitude;
camera.fieldOfView = DefaultFOV + acc*zoomRatio;
}
This is what it looks like on the side panel.
http://i.stack.imgur.com/lYJP7.jpg
The area that says none (transform) is the place that should be variable dependant on the currently selected car.
Now, Here is my other script being the CharacterSelectScript
#pragma strict
//this is the currently selected Player. Also the one that will be saved to PlayerPrefs
var selectedPlayer : int = 0;
function Update()
{
if (Input.GetMouseButtonUp (0)) {
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 100))
{
// The pink text is where you would put the name of the object you want to click on (has attached collider).
if(hit.collider.name == "Player1")
SelectedCharacter1(); //Sends this click down to a function called "SelectedCharacter1(). Which is where all of our stuff happens.
if(hit.collider.name == "Player2")
SelectedCharacter2();
if(hit.collider.name == "Player3")
SelectedCharacter3();
}
else
{
return;
}
}
}
function SelectedCharacter1() {
Debug.Log ("Character 1 SELECTED"); //Print out in the Unity console which character was selected.
selectedPlayer = 1;
PlayerPrefs.SetInt("selectedPlayer", (selectedPlayer));
}
function SelectedCharacter2() {
Debug.Log ("Character 2 SELECTED");
selectedPlayer = 2;
PlayerPrefs.SetInt("selectedPlayer", (selectedPlayer));
}
function SelectedCharacter3() {
Debug.Log ("Character 3 SELECTED");
selectedPlayer = 3;
PlayerPrefs.SetInt("selectedPlayer", (selectedPlayer));
}
How would I get it so that the SelectedPlayer changes the transform in the first script?
Any ideas?
I also have the prefab script which probably isnt important.
Also, should I join both scripts into one?
OVERALL GOAL: Have the camera change target to the selected car
i'm a newbie and i'm terrible at english but hopefully you can understand my problem
i create a simple space shooting game with easeljs, when i tried to create multiple bullets and assign an onTick handle to each one, i relize just one bullet fire out. Here is the code:
//handle fire(shooting)
if(fire && cd === 0){
for(var i=0; i<5; i++){
//codartjs.Bullet is a class extend createjs.Bitmap
var b = new codartjs.Bullet(bullet_img);
b.x = 200;
b.y = 200;
stage.addChild(b);
b.onTick = function(){
//this event handler work for only first instance
b.y -= 10;
};
}
cd = 100;
setTimeout(function(){
cd = 0;
},100);
}
What you can also try is having a central ticker and loop through each bullet element and update its position that way. Here is quick demo that will illustrate my point.
<script>
var canvas, stage;
var bullets;
var speed;
function init() {
stage = new createjs.Stage("test");
bullets = [];
var bg = new createjs.Shape();
bg.graphics.beginFill("#FFFFFF").drawRect(0, 0, stage.canvas.width, stage.canvas.height).endFill();
bg.cache(0, 0, stage.canvas.width, stage.canvas.height);
speed = 15;
stage.onClick = handleClick;
stage.mouseEnabled = true;
stage.enableMouseOver(10);
createjs.Ticker.setFPS(24);
stage.addChild(bg);
createjs.Ticker.addListener(window);
}
function getSprite() {
var s = new createjs.Shape();
s.graphics.beginFill("#000000").drawCircle(0, 0, 10).endFill();
return s;
}
function tick() {
for(var i=0;i<bullets.length;i++) {
var s = bullets[i];
s.x += speed;
}
stage.update();
}
function handleClick(event) {
var s = getSprite();
s.x = event.stageX;
s.y = event.stageY;
bullets.push(s);
stage.addChild(s);
}
</script>
Hope this helps.