Get texture of Sprite in cocos 2dx - ios

i have developed cocos 2dx game in which i am running animation in the Sprite in which i want to get the current texture name for that i have tried following code:
CCSpriteFrame *frameN = fisherManBoat->displayFrame();
frameName = frameN->_textureFilename;
But it gives me error that textureFilename is protected so how can i resolve it ? If it doesn't work then what else i can try? Because there is a button on the screen on which i tap and animation runs, i want to make it smooth. So, that if animation is in between on taping again it doesn't starts from again but from its current point.

if you want to access the _textureFilename variable the you need to modify the CCSpriteFrame.h file.
First you need to find this code in CCSpriteFrame.h file
protected:
Vec2 _offset;
Size _originalSize;
Rect _rectInPixels;
bool _rotated;
Rect _rect;
Vec2 _offsetInPixels;
Size _originalSizeInPixels;
Texture2D *_texture;
std::string _textureFilename;
PolygonInfo _polygonInfo;
And cut below line from this code
std::string _textureFilename;
now you have to paste it on top of CCSpriteFrame.h file where Public Scope is define.
class CC_DLL SpriteFrame : public Ref, public Clonable
{
public:
std::string _textureFilename;
I hope it will help you. Thanks.

Related

How do I only respond to touches within a UI Image?

I have been wracking my brain and using every Google search phrase I can think of and have yet to find a solution.
I have a Unity app with a 3D scene and UI elements that float over it. There is one UI element that is an image of a protractor. That image needs to be drug around the scene, rotated, and scaled. All of that works, the only catch is that is doesn't matter if the user touches the protractor or somewhere else, the protractor always reacts.
I started by looking for something along the lines of Swift's someCGRect.contains(someCGPoint) so that I could ignore anything that isn't in the bounds of the protractor. Image doesn't seem to have such a property so I did lots of other searching.
I finally found this video; https://www.youtube.com/watch?v=sXc8baUK3iY that has basically what I'm looking for… Except is doesn't work.
The video uses a collider and rigid body and then in code checks to see if the collider overlaps the touch point. Looks like exactly what I need. Unfortunately, no touches ever overlap with the collider no matter where they are. After some Debug.Log I found that the extents of the collider are reported as (0, 0, 0). This is clearly why none of the touches overlap with it, but I can't figure out how to make the extents be anything other than 0.
Here is the info from the colliders and rigid body attached to the image:
Box Collider 2D:
Used by Composite: true
Auto Tiling: false
Offset: (0,0)
Size: (1,1)
Rigidbody 2D:
Body Type: Kinematic
Material: None (Physics Material 2D)
Simulated: true
Use Full Kinematic Contact: false
Collision Detection: Discrete
Sleeping Mode: Start Awake
Interpolate: None
Constraints: None
Composite Collider 2D:
Material: None (Physics Material 2D)
is Trigger: false
Used By Effector: false
Offset: (0,0)
Geometry Type: Polygons
Generation Type: Synchronous
Vertex Distance: 0.0005
There is a button that turns the protractor on and off by use of the following code:
public void toggle() {
this.enabled = !this.enabled;
this.gameObject.SetActive(this.enabled);
}
The protractor starts life visible but Start() calls toggle() straight away so the user sees it as starting out off.
This is the code that performs the test to see if the touches should be responded to:
void checkTouches() {
if (Input.touchCount <= 0) {
return;
}
bool oneTouchIn = false;
Collider2D collider = GetComponent<Collider2D>();
Debug.Log("🔵 The bounds of the collider are: " + collider.bounds);
// The above always logs the extents as (0,0,0).
foreach (Touch touch in Input.touches) {
Vector2 touchPos = Camera.main.ScreenToWorldPoint(touch.position);
if(collider.OverlapPoint(touchPos)) {
// Since the extents are all 0 we never find any overlaps
oneTouchIn = true;
break;
}
}
if (!oneTouchIn) {
return; // Always ends up here
}
// We must have at least one touch that is in our bounds.
// Do stuff with the touch(es) here…
}
I've been doing iOS development with Objective-C since the SDK was released and with Swift since it come out but I'm very new to Unity. I'm sure the issue is me missing something silly, but I can't find it.
Does anyone know what I'm missing to make the current version work or an alternate way of only responding to touches that are in bounds?
Image doesn't seem to have such a property
No the Image componemt itself doesn't have that ...
But the rect property of the RectTransform component each UI GameObject has.
It is called Contains. So you could do e.g.
RectTransform imgRectTransform = imageObject.GetComponent<RectTransform>();
Vector2 localTouchPosition = imgRectTransform.InverseTransformPoint(Touch.position);
if (imgRectTransform.rect.Contains(localToichPosition)) { ... }
Alternatively you could use the IPointerEnterHandler and IPointerExitHandler Interfaces in a component on the target Image like e.g.
public class DragableHandler : MonkBehaviour, IPointerEnterHandler, IPointerExitHandler
{
public bool IsHover {get; private set; }
//Detect if the Cursor starts to pass over the GameObject
public void OnPointerEnter(PointerEventData pointerEventData)
{
//Output to console the GameObject's name and the following message
Debug.Log("Cursor Entering " + name + " GameObject");
IsHover = true;
}
//Detect when Cursor leaves the GameObject
public void OnPointerExit(PointerEventData pointerEventData)
{
//Output the following message with the GameObject's name
Debug.Log("Cursor Exiting " + name + " GameObject");
IsHover = false;
}
}
and than in your script check it using
if(imageObject.GetComponent<DragableHandler>().IsHover) { ... }
just also make sure that we the EventSystem you also add Touch Input Module and check the flag Force Module Active.

Need help - Monogame 2d water reflection

Ok so i am following this tutorial Water Reflection XNA and when i adjust code with monogame i cant get final result.
So here is my LoadContent code:
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
texture = Content.Load<Texture2D>("test");
effect = Content.Load<Effect>("LinearFade");
effect.Parameters["Visibility"].SetValue(0.7f);
}
and my Draw code:
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
//effect.CurrentTechnique.Passes[0].Apply();
spriteBatch.Draw(texture, new Vector2(texturePos.X, texturePos.Y + texture.Height), null, Color.White * 0.5f, 0f, Vector2.Zero, 1, SpriteEffects.FlipVertically, 0f);
spriteBatch.End();
spriteBatch.Begin();
spriteBatch.Draw(texture, texturePos, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
and finally my .fx file: LinearFade
So the problem starts when i apply effect. My texture just disappear and if i comment effect part in Draw method i get mirror image with fade (messing with alpha "Color.White * 0.5f") but without fade effect like he have on tutorial from middle of picture to the bottom of picture. I still dont have much experience in monogame and shader but i am learning.
If any1 know how to fix this or how to make it like on tutorial above it would be nice. Btw sry for bad english not my main language.
Ok no need for help i got it after 2 day of thinking i know the answer. The thing is that you need default vertex shader input and output and then shader is working. So if any1 have problem with shaders in monogame first see if you have default vertex input and output. Will put solution code so if some1 doing same tutorial or similer thing so they know what is the problem.
Solution: Working Effect.fx

SetMatrix has no effect (WebCamTexture Unity)

I'm using WebCamTexture to get input from the camera (iOS&Android). However, since this is raw input, the rotation is wrong when rendered to a texture. I read around a lot, and found this (look at the bottom): WebCamTexture rotated and flipped on iPhone
His code (but with test-values):
Quaternion rotation = Quaternion.Euler(45f, 30f, 90f);
Matrix4x4 rotationMatrix = Matrix4x4.TRS(Vector3.zero, rotation, new Vector3(1, 1, 1));
material.SetMatrix("_Rotation", rotationMatrix);
But whatever value I use, nothing happens (neither in the editor or on devices)...
Thanks!
Edit
After some intense testing, I found that material.SetMatrix, SetFloat, SetWhatever has NO effect (not setting the value) unless it's declared inside the "Properties"-block. Looking at unity:s own example, this should't have to (and can't) be done for a matrix (can't be declared inside Properties, only inside the CGProgram). So... How do you set a matrix then? Or what else am I doing wrong?
You should be using: WebCamTexture.videoRotationAngle
its designed to solve exactly this problem, read more about this here.
Example code:
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
public WebCamTexture webcamTexture;
public Quaternion baseRotation;
void Start() {
webcamTexture = new WebCamTexture();
renderer.material.mainTexture = webcamTexture;
baseRotation = transform.rotation;
webcamTexture.Play();
}
void Update() {
transform.rotation = baseRotation * Quaternion.AngleAxis(webcamTexture.videoRotationAngle, Vector3.up);
}
}
Just rotate the camera to 90 degrees along the z axis (the camera is which is rendering the webcamtexture gameobject).

BasicEffect fog, code used

I want to copy BasicEffect's fog method to use in my own shader so I don't have to declare a basiceffect shader and my own. The HLSL code of the basic effect was released with one of the downloadable samples on XNA Creators Club a while ago and I thought the method needed would be found within that HLSL file. However, all I can see is a function being called but no actual definition for that function. The function called is:
ApplyFog(color, pin.PositionWS.w);
Does anybody know where the definition is and if it's freely acceptable. Otherwise any help on how to replicate it's effect would be great.
I downloaded the sample from here.
Thanks.
Edit: Stil having problems. Think it's to do with getting depth:
VertexToPixel InstancedCelShadeVSNmVc(VSInputNmVc VSInput, in VSInstanceVc VSInstance)
{
VertexToPixel Output = (VertexToPixel)0;
Output.Position = mul(mul(mul(mul(VSInput.Position, transpose(VSInstance.World)), xWorld), xView), xProjection);
Output.ViewSpaceZ = -VSInput.Position.z / xCameraClipFar;
Is that right? Camera clip far is passed in as a constant.
Heres an example of how to achieve a similar effect
In your Vertex Shader Function, you pass the viewspace Z position, divided by the distance of your farplane, that gives you a nice 0..1 mapping for your depthvalues.
Than, in your pixelshader, you use the lerp function to blend between your original color value, and the fogcolor, heres some (pseudo)code:
cbuffer Input //Im used to DX10+ remove the cbuffer for DX9
{
float FarPlane;
float4 FogColor;
}
struct VS_Output
{
//...Whatever else you need
float ViewSpaceZ : TEXCOORD0; //or whatever semantic you'd like to use
}
VS_Output VertexShader(/*Your Input Here */)
{
VS_Output output;
//...Transform to viewspace
VS_Output.ViewSpaceZ = -vsPosition.Z / FarPlane;
return output;
}
float4 PixelShader(VS_Output input) : SV_Target0 // or COLOR0 depending on DX version
{
const float FOG_MIN = 0.9;
const float FOG_MAX = 0.99;
//...Calculate Color
return lerp(yourCalculatedColor, FogColor, lerp(FOG_MIN, FOG_MAX, input.ViewSpaceZ));
}
I've written this from the top of my head, hope it helps.
The constants i've chose will give you a pretty "steep" fog, choose a smaller value for FOG_MIN to get a smoother fog.

How can I fill an actionscript 3 polygon with a solid color?

I'm building a map editor for a project and need to draw a hexagon and fill it with a solid color. I have the shape correct but for the life of me can't figure out how to fill it. I suspect it may be due to whether the thing is a Shape, Sprite or UIComponent. Here is what I have for the polygon itself:
import com.Polygon;
import mx.core.UIComponent;
public class greenFillOne extends UIComponent {
public var hexWidth:Number = 64;
public var hexLength:Number = 73;
public function greenFillOne() {
var hexPoly:Polygon = new Polygon;
hexPoly.drawPolygon(40,6,27+(hexWidth*.25),37,0x499b0e,1,30);
addChild(hexPoly);
}
}
The Polygon class isn't a standard Adobe library, so I don't know the specifics. However, assuming that it uses the standard flash API, it should be no problem to add some code to extend the function. You just need to make sure you're doing a graphics.beginFill before the graphics.lineTo / graphics.moveTo functions. And then finish with graphics.endFill.
e.g.,
var g:Graphics = someShape.graphics;
g.beginFill(0xFF0000,.4); // red, .4 opacity
g.moveTo(x1,y1);
g.lineTo(x2,y2);
g.lineTo(x3,y3);
g.lineTo(x1,y1);
g.endFill();
This will draw a triangle filled with .4 red.
I'll put this here because answering it as a comment to Glenn goes past the character limit. My actionscript file extends UIComponent. When I created a variable hexPoly:Polygon = new Polygon; it would render the outline of the hex, but would not fill it no matter what I did. I examined polygon.as and duplicated the methods, but as a sprite and it worked. So, I need to figure out how to wrap the polygon as a sprite, or just leave it as is.
var hexPoly:Sprite = new Sprite;
hexPoly.graphics.beginFill(0x4ea50f,1);
hexPoly.graphics.moveTo(xCenter+(hexWidth*.25)+Math.sin(radians(330))*radius,offset+(radius-Math.cos(radians(330))*radius));
hexPoly.graphics.lineTo(xCenter+(hexWidth*.25)+Math.sin(radians(30))*radius,offset+(radius-Math.cos(radians(30))*radius));
hexPoly.graphics.lineTo(xCenter+(hexWidth*.25)+Math.sin(radians(90))*radius,offset+(radius-Math.cos(radians(90))*radius));
hexPoly.graphics.lineTo(xCenter+(hexWidth*.25)+Math.sin(radians(150))*radius,offset+(radius-Math.cos(radians(150))*radius));
hexPoly.graphics.lineTo(xCenter+(hexWidth*.25)+Math.sin(radians(210))*radius,offset+(radius-Math.cos(radians(210))*radius));
hexPoly.graphics.lineTo(xCenter+(hexWidth*.25)+Math.sin(radians(270))*radius,offset+(radius-Math.cos(radians(270))*radius));
hexPoly.graphics.endFill();
addChild(hexPoly);

Resources