Unity 5: how to zoom and translate an object from a grid layout to the center of the screen - unity3d

I'm trying to create a scroll grid view in which every cell object is tapable.
When a cell object is tapped I want to scale and traslate it to the center of the screen and render it above other cells.
I was able to make it tapable and scale it in its position. Now I want to move the cell object to the center of the screen and render it above other cells.
I've tried many solutions but none of them works.
This is my hierarchy:
This is the grid in normal state:
This is the grid when a cell was tapped:
I'm populating the grid from a C# script dynamically.
void Populate()
{
GameObject cardContainerInstance, cardInstance;
foreach (var c in cardsCollection.GetAll())
{
if (c.IsOwned)
{
cardContainerInstance = Instantiate(cardContainer, transform);
cardInstance = cardContainerInstance.transform.Find("Card").gameObject;
var cardManager = cardInstance.GetComponent<CardManager>();
cardManager.card = c;
cardManager.AddListener(this);
}
else
{
Instantiate(cardSlot, transform);
}
}
}
public void OnCardClick(GameObject cardObject, Card card)
{
Debug.Log("OnCardClick " + card.name);
if (openedCard != null) {
if (openedCard.Number == card.Number)
{
CloseCard(openedCardObject);
}
else
{
CloseCard(openedCardObject);
OpenCard(cardObject, card);
}
}
else
{
OpenCard(cardObject, card);
}
}
void OpenCard(GameObject cardObject, Card card)
{
//cardObject.GetComponent<Canvas>().sortingOrder = 1;
var animator = cardObject.GetComponent<Animator>();
animator.SetTrigger("Open");
openedCard = card;
openedCardObject = cardObject;
}
void CloseCard(GameObject cardObject)
{
var animator = cardObject.GetComponent<Animator>();
animator.SetTrigger("Close");
openedCard = null;
openedCardObject = null;
}
I can't figure out how to move the cell to the center and render it above others.
Note that all is animated using an animator attached to the object itself.
Could anyone help me please? Thank you very much!
EDIT: more details
All cell object have the following hierarchy:
where:
CardContainer is an empty object added to use animator on Card child object
Card is the object itself that has a script, a canvas renderer and an animator
StatsImage is the object that slide out when the card is tapped
Image is a calssic UIImage with Image script, Shadow script and canvas renderer
Other component are simple texts.
EDIT: fix in progress
Trying to apply this suggestions I was able to manage the rendering order (as you see on the image below) but it seems that prevent touch events to be detected on the game object.
I've added a GraphicsRaycaster too and now the bottom horizontal scroll view scrolls again but only if I click and drag a card.
Moreover, with the GraphicsRaycaster, the main grid card still are not clickable and it's possible to open the card only if it is behind the bottom panel (if I click on the red spot in the image below the card behind the panel receives che click)
This is the CardContainer at runtime(note that I'm attaching new Canvas and GraphicsRaycaster on the CardContainer, which is the "root" element):

You didn't clarify whether you are using a sprite renderer or some other method but here is an answer for each.
Sprite renderer:
this the simple one. In each sprite renderer, there is a variable called "sortingOrder" in script and "Order in layer" in the inspector. sprite renderer with sorting Orders that are higher is rendered first. All you would need to do is call:
cardObject.GetComponent<SpriteRenderer>().sortingOrder = 1;
when you click the card, and
cardObject.GetComponent<SpriteRenderer>().sortingOrder = 0;
when you unclick it. I hope that makes sense!
Other Method:
this one is a bit harder and I would suggest that you switch to sprite renderers and it will be much easier and more stable down the road, but I can understand if you have already written a lot of scripts and don't want to go back and change them.
Anyway, all you will need to do Is create two layers: cardLower and cardUpper. then create a new camera and call it topCamera. now under the top camera object in the inspector, change the culling mask (it's near the top) and make sure cardUpper is selected. then change the Clear flags (first one) to "Don't Clear" finally change the depth to 0 (if that doesn't work change it to -2). Now objects in the cardUpper will always be rendered above everything else. You can change the layer through script with
cardObject.layer = "cardUpper"
or
cardObject.layer = "cardLower"
I hope that helps!

Ok, so its pretty simple. So you are going to want to add another canvas component to the game object, and check the override sorting to true. Then use
cardObject.GetComponent<Canvas>().sortingOrder = 1;
to place it in the front and
cardObject.GetComponent<Canvas>().sortingOrder = 0;
to put it in the back.
you are also going to need to put a GraphicsRaycaster on to each of the cardObjects
Ignore my other answer about sprite renderers, they are not needed here

Related

Unity, scalling the width of a dynamically created Gameobject in a a scroll view content box

I am trying to add 100 dynamically created buttons to a scroll view in Unity, but I have a problem letting the scroll view automatically adjust the width of the buttons to match the width of my screen.
When I tried to add the buttons manually it worked fine , but when I do this by code I get another results.
The code I am using :
public GameObject button;
public GameObject scrollviewcontents;
void Start()
{
for (int i =0; i<=100;i++) {
GameObject dbutton = Instantiate(button);
dbutton.name = i.ToString();
dbutton.transform.parent = scrollviewcontents.transform;
}
}
and The results I get :
Results
Results with comments
I just want the buttons to look like as they are added manually, any help ???
By default when instantiating an object the object keeps the same world space position, rotation and scale as before. try this instead:
dbutton.transform.SetParent(scrollviewcontents.transform, false);

Graphics.RenderTexture() causes extra image to appear on canavas

I have some code like this:
readonly Rect WORK_SOURCE_RECT = new Rect(0f, 0f, 1f, 1f);
Color[] workPixels;
void Start() {
Texture2D workTexture = new Texture2D(256, 256, GraphicsFormat.R8G8B8A8_UNorm,
TextureCreationFlags.None);
workPixels = workTexture.GetPixels();
}
void OnGUI() {
workTexture.SetPixels(workPixels);
workTexture.Apply();
Graphics.DrawTexture(toRect, workTexture, WORK_SOURCE_RECT,
0, 0, 0, 0, renderColor);
}
void Update() {
// Omitted - Some changes are made by code here to the workPixels array.
}
The call to Graphics.DrawTexture() correctly draws the content of workTexture to the screen, just how I want it. But there is a strange side effect...
Any other GUI that is drawn inside of a scene object containing a Canvas component, will show an extra Y-reversed copy of the work texture. (Nevermind the reversal--not the issue.) I don't know why this extra image is drawn. It seems like there is a shared resource between two GUI things I'd hoped were completely unrelated.
In the image shown below, the reversed-face on the right is the unwanted extra render. Strangely it appears when I move to the right side of my scene, so it's like it is in world space. But it will update when GUI-based elements like subtitles are shown.
On Unity 2019.4.13f1 with MacOS.
The solution I found that resolved my problem was camera stacking. I created a second camera that was culled to just UI layer. The first camera had UI layer removed from culling. And then the calls to Graphics.DrawTexture() no longer appeared on the canvas used for UI.

Dynamically added LineRenderer doesn't show in game view

I add some line dynamically and they appear in the scene view perfectly, but not in game view. The z indexes are properly set, I use different layer just for the lines. I tried changing the camera clipping planes values, culling mask is on everything.
void Update()
{
Vector2 mousePos;
if (Input.GetMouseButtonDown(0))
{
Vector3 closeToPoint = IsClickCloseToPoint();
if (closeToPoint.z != -10000f)
{
GameObject newObj = Instantiate(lineGenerator);
startMousePos = closeToPoint;
newLine = newObj.GetComponent<LineRenderer>();
newLine.transform.SetParent(parentObject.transform);
newLine.positionCount = 2;
}
}
if (Input.GetMouseButton(0))
{
if (newLine != null)
{
mousePos = Input.mousePosition;
newLine.SetPosition(0, new Vector3(startMousePos.x, startMousePos.y, -5f));
newLine.SetPosition(1, new Vector3(mousePos.x, mousePos.y, -5f));
distance = (mousePos - startMousePos).magnitude;
distanceText.text = distance.ToString("F2");
}
}
if (Input.GetMouseButtonUp(0))
{
if (newLine != null)
{
newLine = null;
}
}
}
You are drawing everything on a canvas. But LineRenderer is not a UI component and therefore is not shown on the canvas.
If you want to work with LineRenderer nontheless check this info in Unity Answers. The basic idea is to have the canvas set up as Screen Space and increase the width of the lines. Don't forget to assign the camera.
i think you need to put a material on the lineRenderer. What you see in the scene view is the "non material" texture that doesn't appear in game view :)
I hope that help :)
Raph
The problem was that the coordinates are different in the scene view and the game view, or at least you have to design to the game view, not the scene view. My lines were present in the game view, but they were out of the canvas. I used Camera.main.ScreenToWorldPoint(Vektor3) to convert every vektor.
I can't see the Inspector settings of your LinRenderer but I suspect that you have
Alignment set to Transform Z
Lines face the Z axis of the Transform Component.
And thos becomes completely invisible if your orthographic Camera looks exactly in Z direction onto it.
Try and change the Alignment to View.
Also note that literally nothing is rendered on top of a ScreenSpace Overlay Canvas. It is one of the last things to be rendered in a frame.

How to clone a node to appear exactly on top in a different pane

In my (full-screen) program I have several items displayed in a layout. What I would like to do is that when I tap or click on a item is to show a full screen editor. The idea is to have transition from the item shown to the editor.
When the editor is shown I first display a semi-transparent view on top of the stackpane, underneath the other items are still visible. The selected item should 'move' to the upper layer, and then start to transform to its editor shape. Closing the editor should of course be a reverse course of actions.
The first attempt was to move the from its container to the upper layer, but JavaFX complained about the bound properties. I rather not have to code a whole bunch of bind/unbinds, so I assumed this was not the route.
My next attempt was something like this:
private volatile FullScreenService fullscreenService;
private void showFullPhoto(MouseEvent e) {
FullScreenService service = fullscreenService;
if (service != null) {
try {
Node node = (Node) e.getSource();
ImageView photoView = (ImageView)node.lookup("#image");
Image image = photoView.getImage();
Pane pane = new Pane();
pane.setPrefSize(1920d, 1080d);
ImageView copy = new ImageView(image);
copy.setRotate(node.getRotate());
node.setVisible(false);
Bounds bounds = photoView.localToScene(photoView.getBoundsInLocal());
copy.setLayoutX(bounds.getMinX());
copy.setLayoutY(bounds.getMinY());
pane.getChildren().add(copy);
service.requestFullScreen(pane);
} catch (InUseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
The idea is to hide the original view and 'clone' the part that should be shown (and then transitioned). In this case I extract the image part out of a photo (that also has a border and caption), and make a copy on the editor screen.
However the location of the image does not match the original location exactly, it is off by a couple of pixels, making the image 'jump'.
I've created the pane to be exact the size of the screen, so I thought I could assume scene coordinates are the same as the new node's coordinates.
Abstracting my question: given two overlapping panes, how to make sure a node is exactly on top of another node?

Move a particular sprite to a target position after clicking the button in unity 4.6

I have just started unity. I have 4 Images(sprites) aligned in a grid.
As soon as i touch the particular chocolate, its texture changes[I wrote a code for that]. There is a button on screen.After pressing the button, I want to move only those chocolates whose texture has been changed.
I know the following move code but i don't know how to use it here.
void Update () {
float step=speed*Time.deltaTime;
transform.position=Vector3.MoveTowards(transform.position,target.position,step);
}
I just don't know to move that particular sprite whose texture is changed. Thanks
Do you want to be moving the sprites over the course of a duration or instantly?
If it's over the course of a duration I suggest you use Lerp. You can Lerp between two Vector.3's in a time scale. Much cleaner and once learned a very useful function.
Code examples below:
http://docs.unity3d.com/ScriptReference/Vector3.Lerp.html
http://www.blueraja.com/blog/404/how-to-use-unity-3ds-linear-interpolation-vector3-lerp-correctly
However if you want to move it instantly. This can be done very easily using the built in localPosition properties which you can set in or outside the object.
Set your changed sprites Bool moved property (create this) to true on click (if you're using Unity 4.6 UI canvas then look at the IClick interfaces available for registering mouse activity in canvas elements) and then when you press the button, loop through a list in a handler file which contains all your button texture objects and move those that the moved property is set to true for.
foreach(GameObject chocolate in chocolateList)
{
if (chocolate.moved == true)
{
gameObject.transform.localPosition.x = Insert your new x position.
gameObject.transform.localPosition.y = Insert your new y position.
}
}
However please do clarify your intentions so I can help further.
EDIT 1:
I highly suggest you make your sprites an object in the canvas for absolute work clarity. This makes a lot of sense as your canvas can handle these type of things much better. Use Image and assign your image the sprite object (your chocolate piece), define it's width and height and add a script to it called "ChocolatePiece", in this script create two public variables, bool moved and int ID, nothing else is required from this script. Save this new object as your new prefab.
Once you've done this in a handler script attached to an empty gameobject in your canvas make a list of gameobjects:
List<GameObject> chocolatePieces = new List<GameObject>();
You'll want to at the top of your handler script define GameObject chocolatePiece and attach in your inspector the prefab we defined earlier. Then in Start(), loop the size of how many chocolate pieces you want, for your example lets use 4. Instantiate 4 of the prefabs you defined earlier as gameobjects and for each define their properties just like this:
Example variables:
int x = -200;
int y = 200;
int amountToMoveInX = 200;
int amountToMoveInY = 100;
Example instantiation code:
GameObject newPiece = (GameObject)Instantiate(chocolatePiece);
chocolatePieces.Add(newPiece);
newPiece.GetComponent<ChocolatePiece>().ID = i;
newPiece.transform.SetParent(gameObject.transform, false);
newPiece.name = ("ChocolatePiece" + i);
newPiece.GetComponent<RectTransform>().localPosition = new Vector3(x, y, 0);
From this point add to your positions (x by amountToMoveInX and y by amountToMoveInY) for the next loop count;
(For the transform.position, each count of your loop add an amount on to a default x and default y value (the position of your first piece most likely))
Now because you have all your gameobjects in a list with their properties properly set you can then access these gameobjects through your handler script.