Draw 3D GameObject above GUI in Unity - c#

I would like to draw a GameObject in front of all other components in my project and GUI Textures as well.
I created a second Camera and set Depth and Layer but it still not work. I hope you can help me to find the error or something I forgot.
Here is my MainScript which is drawing a simple Texture:
using UnityEngine;
using System.Collections;
public class MainScript : MonoBehaviour
{
Texture2D texture;
// Use this for initialization
void Start()
{
texture = new Texture2D(Screen.width, Screen.height);
for (int y = 0; y < texture.height; y++)
{
for (int x = 0; x < texture.width; x++)
{
texture.SetPixel(x, y, Color.blue);
}
}
texture.Apply();
}
void OnGUI()
{
GUI.DrawTexture(new Rect(0, 0, texture.width, texture.height), texture);
}
}
I also created two cameras and a GameObject which displays a GUI Texture. The Texture is visible in the preview screen but on runtime the Texture which is drawing in the MainScript is foregrounded.
I made two more Screenshots of my Camera Objects. See here:
I can also supply the whole project for you. It is just a basic test project.
Here is the link to the Project in Google Drive: Download

set depth of camera2 to camera1.depth+1, Clear Flags of camera2 to depth only and Clear Flags of camera1 to skybox. Uncheck GUILayer at Camera2 and check GUILayer in camera1. That should do it...

You cannot draw 3D objects in front of the GUI elements, OnGUI code always renders in top of everything.
To achieve this you can use Render Textures (Unity Pro only): have two cameras in your scene, place your 3D objects in one camera, render this camera to a texture, and finally use that texture as the source of a GUI.DrawTexture().

Related

I want to do translate, rotate and scale while merging the two textures

First of all, please understand that sentences may not be smooth using a translator.
I'm going to combine the two textures and create them into one texture.
Example) 1. image__ 2. image__ 3. result__
A simple combination of two textures is not a problem.
The problem is that translate, rotate and scale should be applied to one texture and merged, but I can't think of a way. I'd appreciate it if you could help me.
here my code :
Texture2D CombineTexutes(Texture2D _textureA, Texture2D _textureB, int startX = 0, int startY = 0)
{
//Create new textures
Texture2D textureResult = new Texture2D(_textureA.width, _textureA.height);
//create clone form texture
textureResult.SetPixels(_textureA.GetPixels());
//Now copy texture B in texutre A
for (int x = startX; x < _textureB.width + startX; x++)
{
for (int y = startY; y < _textureB.height + startY; y++)
{
Color c = _textureB.GetPixel(x - startX, y - startY);
if (c.a > 0.0f) //Is not transparent
{
//Copy pixel colot in TexturaA
textureResult.SetPixel(x, y, c);
}
}
}
//Apply colors
textureResult.Apply();
return textureResult;
}
This is relatively tricky with pixel transformations. You would have to read up on various algorithms for every of those tasks.
A much easier solution would be to use game objects with sprite renderers and then render everything onto a "render texture" (if you really need a texture).
Game objects with a sprite renderer can be easily rotated, scaled etc.
Your result image does look as if it was actually deforming the sprite though, not just scaled in a direction.
If that's your goal, then I'd recommend looking at the Animation 2D package. That allows you to do near anything with sprites.

How to give the camera's edge collision in Unity

I am making a 2D game in Unity, and in this game, the camera will not need to move. As such, I would like to constrain the player's movement within the camera border, preferably with collision instead of just based on the player's transform. Honestly, I have no idea where to start doing something like this, but I assume it would involve some scripting. I am pretty comfortable with scripting at this point, but if your answer includes scripting, I would appreciate it if it would include thorough explanations of everything that is going on. By the by, I am using C#.
If the camera is in orthographic mode, you can use EdgeCollider2D to do this, finding the world positions of the corners of the screen using ScreenToWorldPoint to then determine the shape of the EdgeCollider2D.
The Unity Community UnityLibrary Github has an example (copied below):
// adds EdgeCollider2D colliders to screen edges
// only works with orthographic camera
using UnityEngine;
using System.Collections;
namespace UnityLibrary
{
public class ScreenEdgeColliders : MonoBehaviour
{
void Awake ()
{
AddCollider();
}
void AddCollider ()
{
if (Camera.main==null) {Debug.LogError("Camera.main not found, failed to create edge colliders"); return;}
var cam = Camera.main;
if (!cam.orthographic) {Debug.LogError("Camera.main is not Orthographic, failed to create edge colliders"); return;}
var bottomLeft = (Vector2)cam.ScreenToWorldPoint(new Vector3(0, 0, cam.nearClipPlane));
var topLeft = (Vector2)cam.ScreenToWorldPoint(new Vector3(0, cam.pixelHeight, cam.nearClipPlane));
var topRight = (Vector2)cam.ScreenToWorldPoint(new Vector3(cam.pixelWidth, cam.pixelHeight, cam.nearClipPlane));
var bottomRight = (Vector2)cam.ScreenToWorldPoint(new Vector3(cam.pixelWidth, 0, cam.nearClipPlane));
// add or use existing EdgeCollider2D
var edge = GetComponent<EdgeCollider2D>()==null?gameObject.AddComponent<EdgeCollider2D>():GetComponent<EdgeCollider2D>();
var edgePoints = new [] {bottomLeft,topLeft,topRight,bottomRight, bottomLeft};
edge.points = edgePoints;
}
}
}

XNA: How to change texture reference midgame?

I'm currently making a game in XNA. I have been going well so far but I don't know how to change the texture of a sprite whilst running the game. An example of this would be. When the character is still that's one image, then when he walks that's a different image. How would I make this happen?
Run checks and just set the instance's Texture2D texture to some other texture from your preloaded library.
I usually load all the textures in my content folder into a dictionary and use like so:
var StringTextureDic = new Dictionary<string, Texture2D>();
// code that loads all textures into the dictionary, file names being keys
// whenever I need to assign some texture, I do this:
if (!playerIsMoving)
Player.texture = StringTextureDic["player standing"];
if (playerIsMoving)
Player.texture = StringTextureDic["player moving"];
Well, actually, change the player texture midgame is a bad idea. In such cases, i prefer to use a texture sheet.
Rectangle frame;
int curFrame;
int frameWidth;
int frameHeight;
int runAnimationLength;
Update()
{
//Handle your "animation code"
if(playerIsMoving)
curFrame++; //Running
if(curFrame == runAnimationLength)
curFrame =0;
else
curFrame = 0; //Standing still
}
Draw(SpriteBatch spriteBatch)
{
frame = new Rectangle(curFrame*frameWidth,curFrame*frameHeight,frameWidth,frameHeight);
spriteBatch.Draw(
texture,
position,
**frame**,
color,
rotation,
origin,
SpriteEffects.None,
1);
}

Having trouble with Sprite look at mouse in XNA for game

I understand that this question has been answered before and I've done my research trust me.
I'll say this now, this is a project for school but what I want to do this for my own learning considering that I will be going in to game programmer.
This might get messy but ill do my best
so for this its started as a basic shoot em up, we have a
game.cs- contains all the textures vectors what not, and the
entity.cs- has already begun spritebatch for player to call a player.draw (spritebatch) in
game.cs
player.cs- contains the shooting of the bullet and the position
bullet.cs
enemy.cs
So my problem is that I have the code for updating the sprite to look at the mouse then I would use
player.Draw(
playerTexture,
position,
null,
Color.White,
rotation,
spriteOrigin,
1.0f,SpriteEffects.None,0f);
In game.cs draw function, but when I do this I get another sprite (same sprite as my player sprite) that does look at my mouse but I want my other one to look at mouse
But my proff. Wrote the code so that there is an already begun spritebatch in entity.cs
public CEntity(CGame myGame, Texture2D myTexture)
{
game = myGame;
texture = myTexture;
}
/// <summary>
/// Draws the player.
/// </summary>
/// <param name="begunSpriteBatch">Give this function a already begun SpriteBatch.</param>
public void Draw(SpriteBatch begunSpriteBatch)
{
begunSpriteBatch.Draw(texture, position, Color.White);
}
So in game.cs draw function player.draw is called to draw the player, what can I do to get that look at mouse effect for that sprite?
public CPlayer(CGame game, Texture2D playerTexture)
: base(game, playerTexture)
{
texture = playerTexture;
brotation = rotation;
position.X = 400f;
position.Y = 400f;
}
And also player is inherited from entity.
Code for updating the mouse as requested
IsMouseVisible = true;
MouseState mouse = Mouse.GetState();
distance.X = mouse.X - position.X;
distance.Y = mouse.Y - position.Y;
//Math.Atan2((double)mouseState.Y - position.Y, (double)mouseState.X - position.X); was using this //before found a different way
rotation = (float)Math.Atan2(distance.Y, distance.X);
spriteRectangle = new Rectangle((int)position.X, (int)position.Y,//rotation stuff
playerTexture.Width, playerTexture.Height);
spriteOrigin = new Vector2(spriteRectangle.Width / 2, spriteRectangle.Height / 2);

Drawing a "floor" texture

Alright, let's say that I have a tile texture of some floor or something. And I'd like that my player will walk on that.
How can I set this tile to make it a as a floor?
I need this tile texture to be all over the screen width right?
How am I doing it?
Thanks
If you want a really easy way, here it is:
First you create a new Class and name it Tile:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework; // Don't forget those, they will let you
using Microsoft.Xna.Framework.Content; // access some class like:
using Microsoft.Xna.Framework.Graphics; // Texture2D or Vector2
namespace Your_Project _Name
{
class Tile
{
}
{
So far so good, now create the Texture and Position in your class just like this:
namespace Your_Project _Name
{
class Tile
{
Texture2D texture;
Vector2 position;
public void Initialize()
{
}
public void Draw()
{
}
}
{
As you can see I also created two Methods, Initialize and Draw, now we will Initialize our
texture and position for the tile texture in the public void Initialize(),
I don't know how you use your ContentManager but here is a easy way:
public void Initialize(ContentManager Content)
{
texture = Content.Load<Texture2D>("YourfloorTexture"); //it will load your texture.
position = new Vector2(); //the position will be (0,0)
}
Now we need to draw our texture a number of time how will we do that? The way thasc said, the code can be more complex but here is one that you will understand, I will add a SpriteBatch so I can Draw. All this is done in the public void Draw():
public void Draw(SpriteBatch spriteBatch)
{
for (int i=0; i<30;i++) //will do a loop 30 times. Each Time i will =
//a valor from 0 to 30.
{
spriteBatch.Draw(texture, position, Color.White);
//Will draw the texture once, at the position Vector2
//right now position = (0,0)
spriteBatch.Draw(texture, new Vector2((int)i,(int)i), Color.White);
//Will Draw the texture 30 times, the first time on the position (0,0)
//Second Time on (1,1) .. third (2,2) etc...
spriteBatch.Draw(texture, new Vector2((int)position.X + (i * texture.Width), (int)position.Y + (i * texture.Height), Color.White));
//Will Draw the Texture 30 times Spaced by the Width and height
//of the texture (this is the code you need)
}
}
I didn't tried it but it should work, now its just a sample, you can figure out the rest. There is a lot of other methods to do it but this one is really easy. Ok, now the final step is to implement this class so go in your principal class where you have all your code and before this:
public Game1()
Create a new instance of your tile class
Tile tile;
and Initialize it in the protected override void Initialize():
tile = new Tile();
tile.Initialize(Content);
Now you have to draw it on the screen go at the end of the class and find protected override void Draw(GameTime gameTime) and call the draw method of our class:
spriteBatch.Begin();
tile.Draw(spriteBatch);
spriteBatch.End();
This is all the steps to complete a plain simple tile system. As I said there is a lot of others methods you just have to read tutorials about them or create them on your own.
If you don't plan on doing anything extra with the tiled background, I'd recommend thasc's solution and tile the sprite in a single call.
To do that, you create a rectangle as large as your background, and pass SamplerState.LinearWrap to SpriteBatch.Begin, then call Draw on the background rectangle.
Rectangle backgroundRect = new Rectangle(0, 0, backWidth, backHeight);
spriteBatch.Begin(..., ..., SamplerState.LinearWrap, ..., ...);
spriteBatch.Draw(backgroundTexture, backgroundRect, Color.White);
spriteBatch.End();
In case you're curious, what this does is create a single polygon that covers the background area, which will grab coordinates off your texture from 0.0f to backWidth. Textures are usually mapped between (0.0f, 0.0f) and (1.0f, 1.0f), which represent the corners of the given texture. If you go beyond these boundaries, TextureAddressMode defines how these coordinates will be treated:
Clamp will cut down the coordinates back into the 0-1 range.
Wrap will wrap the coordinates back to 0, so 0.0 = 2.0 = 4.0 = etc. and 1.0 = 3.0 = 5.0 = etc.
Mirror will also wrap, but mirroring the texture every other pass, basically going left-to-right-to-left-etc. as the polygon is rendered.

Categories

Resources