Starling stage touch.phase moving sprite to current location of touch on stage - starling-framework

I'm trying to move a sprite object (the hero) to the current location of the began touch event on the stage. Every time I touch on the stage it reads out the current globalX and globalY coordinates, but the sprite disappears from the stage so I don't know what I am doing wrong.
Here is my code:
private function onTouch(e:TouchEvent):void
{
var touch:Touch = e.getTouch(stage);
if(touch)
{
if(touch.phase == TouchPhase.BEGAN)
{
hero.x += touch.globalX;
hero.y += touch.globalY;
trace("Touched stage at position: " + touch)
}
else if(touch.phase == TouchPhase.ENDED)
{
//The Touch ended (MouseUp)
}
else if(touch.phase == TouchPhase.MOVED)
{
//dragging
}
}
}

Probably your hero sprite is added to Spirte with different size than the object you assigned the touch event. You need a sprite with for example screen size and the hero and the event added to it.
Hope that help :)

Related

Stop loop and start again from the beginning

I am trying to include enumerateChildNode with a For Loop. My code is below.
func movement() {
scene?.enumerateChildNodes(withName: "//enemy") {
(node, stop) in
enemyArray.append(node as! SKSpriteNode)
}
for i in enemyArray {
if enemy.position = player.position + 1 {
player.position = player.position + 1
}
continue
}
What the code above does is check for every enemy SKSpriteNode on the screen (lets say it finds 6), and then checks their positions relative to the player. If the players position is near the enemy position, it moves the players position, and then continues the for loop from where it was and checks the players position from the remaining enemies.
However, if the player moves near an enemy position that the for loop already checked (which was false at the time), it will miss that the player is near that enemy. EG: The for loop checks enemies 1,2,3 (finds 3 is near player and moves the player near 2) then checks 4,5,6. It will miss 2...
What I want the code to do
If enemy.position = player.position + 1 {
//move player
*stop the loop, and check the players position from the beginning of the for loop*
}
Call the method again and break out of the loop. But, this causes an infinite loop as you know while posting your question. Not sure how you're planning on changing the value of "i" since it's scope is within the method. Anyways here's how you achieve this:
var array = [1,2,3,4,5,6]
movement()
func movement() {
for i in array {
if i == 3 {
print("hi")
movement()
break
}
}
}

How to make Touch Controls like mini Golf King

Goal
Hello Guys! I am new with unity 3-D . I want to make controls exactly like Mini Golf king . Like when ball stops pointers becomes visible on the screen . On clicking that pointer and dragged its scale changes and points always towards ball.
This is what I want to achieve
MY Approach
Initially according to my knowledge I Have implemented something using ray-cast. In the pointer I placed 3-d pointer as child object of ball . when i touch on the screen I send a ray cast to world from screen that detects Ball if i am touching Ball the i show Pointer and on every point on the screen i am continuously sending ray-casts on the world and changing pointer direction accordingly but i think it is not the good way on performance point
RaycastHit GenerateRayCast(Vector2 position, Camera camera,LayerMask mask) { // GENERATE RAY CAST AT GIVEN DIRECTION IN 3D WORLD
RaycastHit hito;
Ray ray = camera.ScreenPointToRay(position);
Physics.Raycast(ray, out hito, rayLength, mask);
return hito;
}
#endregion
#region Updatemethod
void FixedUpdate () {
if (IsBallInStopPos) { // IF BALL IN STATIC POSITOIN THEN LISTEN FOR TOUCH INPUTS
//if (Input.GetMouseButton(0) && !EventSystem.current.IsPointerOverGameObject())
if (Input.touchCount > 0 && !EventSystem.current.IsPointerOverGameObject()) // CHECK FOR SREEN TOUCH
{
touchInput = Input.touches[0];
// touchInput = Input.mousePosition; // get touch information
hitObject = GenerateRayCast(touchInput.position, Camera.main, mask);
if (touchInput.phase == TouchPhase.Began)
{
if (hitObject.collider.name == "Pointer") { // IF TOUCHED ON POINTER :
if (touchPointSet == false) {
touchPointSet = true;
touchStartPoint = hitObject.point; // SETTING START TOUCH POINT
}
}
}
else if (touchInput.phase == TouchPhase.Moved) {
newScale= Mathf.Clamp (Vector3.Distance(pointerChild.transform.position , hitObject.point),1f,2f);
pointerPivot.transform.localScale = Vector3.one * newScale;// SETTING SCALE ACCORDING TO DRAG VALUE
if (touchPointSet == true) { // WHEN TOUCH DRAGGED AND PREVIOULY POINTER IS TOUCHED ROTATE THE POINTER AT GIVEN DIRECTION
newDirection = new Vector3(hitObject.point.x, transform.position.y, hitObject.point.z);
transform.LookAt(2 * transform.position - newDirection);
canShoot = true;
}
}
}
else if (touchInput.phase == TouchPhase.Ended)
{
if (newScale <= 1f)
return;
if (IsBallInStopPos && canShoot )
{
//shooted = true;
newScale = newScale -1;// AS SCALE VALUE IS BETWEEN 1 AND 2 SO SUBSTACT FROM TO MAKE IT BETWEEN
pointerPivot.gameObject.SetActive(false);
rigidBody.constraints = RigidbodyConstraints.None;
GetComponent<Rigidbody>().AddRelativeForce(new Vector3(0f, 0f, 10000f * newScale));
// Time.timeScale = 2f;
canShoot = false;
IsBallInStopPos = false; // AFTER SHOOT : after the ball is shooted now the ball is not in staticstatic condition
}
}
}

Move object with hinge joint, but keep it connected to hinge

I have multiple spheres in my mobile game that are attached to hinge joints. The spheres are able to swing and knock into each other, causing other spheres to swing. I am creating movement in the spheres by touching on a sphere and dragging it to a new location. Letting go is supposed to cause the sphere that I just moved to swing accordingly.
The issue is that I am able to move the spheres well outside of the space provided by the hinge. I never want the spheres to move anywhere that they wouldn't be able to swing using the hinge. I am able to move the spheres multiple units/meters away from their original position, when ideally I wouldn't be able to move them more than a few centimeters. The spheres should just stop moving if I hit a limit in the hinge.
Here's my code for the script that controls movement of the spheres:
GameObject selectedObject;
Vector3 screenPoint;
Vector3 offset;
void Update () {
if (Input.touchCount == 0)
{
return;
}
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began) // when screen is touched...
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenToWorldPoint(touch.position), Camera.main.transform.forward, out hit)) // ...cast a ray...
{
if (hit.collider.tag == "Sphere") //...and check if ray hits a sphere
{
selectedObject = hit.collider.gameObject;
screenPoint = Camera.main.WorldToScreenPoint(selectedObject.transform.position);
offset = selectedObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, screenPoint.z));
}
}
}
if (touch.phase == TouchPhase.Moved)
{
Vector3 touchPoint = new Vector3(touch.position.x, touch.position.y, screenPoint.z);
Vector3 touchPosition = Camera.main.ScreenToWorldPoint(touchPoint) + offset;
selectedObject.transform.position = touchPosition;
}
}
Any help is greatly appreciated! Let me know if I need to explain more or show a video of the issue.
I know I am a little late but you can use AddForce() and AddTorque() methods on the object you want to move but that works only if you have RigidBody on the object.

How to make Player Model with Nav Mesh Agent to Jump

i have a program code on a Player model with Nav Mesh Agent that allows it to walk around the world when clicked but am trying to make it jump and haven't seem to achieve it.
this is my code, don't know what to add or remove
public class WorldInteraction : MonoBehaviour {
NavMeshAgent playerAgent;
// Use this for initialization
void Start () {
playerAgent = GetComponent<NavMeshAgent> (); //instantiate the nav mesh to PlayerAgent
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown (0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject ()) //condition if the postion is being clicked on a UI is veung clicked
{
GetInteraction (); //call interaction method
}
if (Input.GetMouseButtonDown (1) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject ())
{
transform.Translate (Vector3.up);
}
}
void GetInteraction(){ //this method gets the ray or point clicked and move the player to that point
Ray interactionRay = Camera.main.ScreenPointToRay (Input.mousePosition); //get the point clicked in the world
RaycastHit interactionInfo; //keeps track of the point clicked
if (Physics.Raycast (interactionRay, out interactionInfo, Mathf.Infinity)) //get the point clicked, store it in InteractionInfo and make sure its not out of range by mathf
{
GameObject interactedObject = interactionInfo.collider.gameObject;
if (interactedObject.tag == "Interactable Item") //check if the item point selected is interacrable(cant be move over)
{
interactedObject.GetComponent<Interactable> ().MoveToInteraction (playerAgent); //move playerAgent to the Interactable item, so they could interact(its calling the movetoInteractable method in Interactable class).
} else {
playerAgent.stoppingDistance = 0;
playerAgent.destination = interactionInfo.point; //if its a movable point, player destination is set to that point
}
}
}
}
The NavMeshAgent controls the object in all directions so it will just override your attempt to jump. Make the object with the NavMeshAgent a child of an empty object and just Translate the empty object upwards. Hopefully that helps.

Iphone - CGPointIntersectsRect Collision Problem?

The problem is when the player collides with the blackB the player doesn't stop. It slowly continues through the blackB. The IBAction is being used with a game loop. I need a way to freeze the player completely when it collides with the blackB. Any help is welcome, I am a beginner programmer. Thank you!
player and blackB are both UIImageViews
- (IBAction)right
{
direction = kright;
if (direction == kright)
{
rightMovement = CGPointMake(kMovement,0);
blockVelocity.x += rightMovement.x;
player.center = CGPointMake(player.center.x + blockVelocity.x,player.center.y);
if(CGRectIntersectsRect(player.frame, blackB.frame))
{
if(player.center.x < blackB.center.x)
{
if(blockVelocity.x > 0)
{blockVelocity.x = zero;
}
}
}
}
}
Sort of a sloppy answer, but in pseudo code:
-(IBAction)right {
if (playerCanMove==1) {
//move player
}
}
Set playerCanMove to 1 when the game loads, and set it to 0 on collision.