texture will not load to player in sfml - png

I am trying to load a texture to my player class. I made the function set text to do this operation. but when I call it in the main loop (and I made sure it's not in the poll event) it just shows a white rectangle. I changed it to 32 bits, but it didn't work and then to 8 and that also didn't work (its original bit was 24). I also made sure that it was that the texture wasn't loading, and it is not. all responses are appreciated.
void setText1() {
sf::Texture p1text;
p1text.loadFromFile("player1.png");
rect.setTexture(&p1text);
}
main.cpp
sf::RenderWindow window(sf::VideoMode(800,800), "High noon showdown", sf::Style::Close | sf::Style::Titlebar);
window.setFramerateLimit(60);
player1 player1(50, 70, 85, 325);
player2 player2(50, 70, 715, 325);
player1.setText1();
//game loop
//movement
window.clear(sf::Color(210,180,140,100));
player1.collidewindow1();
player1.drawto1(window);
player2.collidewindow2();
player2.drawto2(window);
window.display();
player1.hpp
#pragma once
#include <SFML/Graphics.hpp>
#include <stdlib.h>
#include <stdio.h>
#include <SFML/Window.hpp>
#include "main.h"
class player1
{
public:
//get player size and position
player1(float x, float y, float px, float py) {
rect.setSize(sf::Vector2f(x,y));
rect.setPosition(sf::Vector2f(px, py));
}
//draw player
void drawto1(sf::RenderWindow &window) {
window.draw(rect);
}
void collidewindow1() {
//Top collision
if(rect.getPosition().y < 0.0f) {
rect.setPosition(rect.getPosition().x, 0.0f);
}
//Bottom collision
if(rect.getPosition().y + rect.getGlobalBounds().height > 800) {
rect.setPosition(rect.getPosition().x, 800 - rect.getGlobalBounds().height );
}
}
void upfalse1() {
up = false;
}
void downfalse1() {
down = false;
}
void moveup1() {
up = true;
if(up == true){
rect.move(0.0f, -5.0f * dt * 32.5f);
}
}
void movedown1() {
down = true;
if(down == true) {
rect.move(0.0f, 5.0f * dt * 32.5f);
}
}
void setText1() {
sf::Texture p1text;
p1text.loadFromFile("p1.png");
rect.setTexture(&p1text);
}
int getx1() {
return rect.getPosition().x;
}
int gety1() {
return rect.getPosition().y;
}
private:
sf::RectangleShape rect;
bool up;
bool down;
};

sf::Sprites need textures to work. They save the textures in pointer form so using temporary variable will not work. You need your texture to either be a dynamic variable or be in a place until the sprite you created is destroyed.
If you don't want to play with dynamic variables i suggest you put the texture variable into a 'player' object.
This is what's breaking your code:
void setText1() {
sf::Texture p1text; <- you create texture
p1text.loadFromFile("player1.png"); <- load the texture
rect.setTexture(&p1text); <- set the rect/sprite with texture
} <- texutre gets deleted thus sprite/rect point to adress with no texture
Fix:
class Player1
{
...
private:
sf::RectangleShape rect;
bool up;
bool down;
sf::Texture texture; <- void setText1() should set this texture
};

Related

I want set 30 rpm in Wheel Collider

I have a robot with a wheel to which I have applied a script to rotate the wheel and a "wheel collider" component with these values:
I would like to know what values ​​I have to modify to get the robot wheel to rotate at 30 rpm, since it is going to move around an office and it is seen to rotate very fast.
Finally, since it was a simple wheel and I just wanted it to give the effect of simple movement, what I did was this script.
public class WheelRotateAroundCylinder : MonoBehaviour
{
private Transform wheel;
private bool rotate = false;
private void Awake()
{
wheel = transform;
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(rotate)
{
wheel.Rotate(0, -2, 0);
}
else
{
wheel.Rotate(0, 0, 0);
}
}
public void isRotate(bool hasRotate)
{
if(hasRotate)
{
this.rotate = true;
}
else
{
this.rotate = false;
}
}
}

HoloLens - How to get webcam texture 2D from Vuforia

I'm developing a Vuforia app for HoloLens by using Unity.
This app displays a simple 3D Object when an image target is detected.
I'm also using the fm Exhibition Tool Pack hololens from the Unity Asset Store in order to stream the app running on HoloLens to a PC.
Everything works fine but when i stream the app to PC i see the 3D Unity scene instead of the room.
So i've tried to get the webcam texture and attach it to a cube inside the scene but the vuforia ARCamera get somehow conflict with it and i can't see anything on the cube. Instead when i run the app inside the Unity Simulator i see myself on the cube.
Is there a way to get the webcam texture 2D from Vuforia and attach it to a GameObject inside the scene? Maybe with the Vuforia.Image class? But i don't know how it works.
Below scripts are compatible with FMETP STREAM.
The scripts are tested on mobile.
using UnityEngine;
using System.Collections;
using Vuforia;
using UnityEngine.UI;
public class VuforiaCamAccess : MonoBehaviour
{
private bool mAccessCameraImage = true;
public RawImage rawImage;
public GameObject Mesh;
private Texture2D texture;
#if UNITY_EDITOR
private Vuforia.PIXEL_FORMAT mPixelFormat = Vuforia.PIXEL_FORMAT.GRAYSCALE;
#else
private Vuforia.PIXEL_FORMAT mPixelFormat = Vuforia.PIXEL_FORMAT.RGB888;
#endif
private bool mFormatRegistered = false;
void Start()
{
#if UNITY_EDITOR
texture = new Texture2D(Screen.width, Screen.height, TextureFormat.R8, false);
#else
texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
#endif
// Register Vuforia life-cycle callbacks:
Vuforia.VuforiaARController.Instance.RegisterVuforiaStartedCallback(OnVuforiaStarted);
Vuforia.VuforiaARController.Instance.RegisterOnPauseCallback(OnPause);
Vuforia.VuforiaARController.Instance.RegisterTrackablesUpdatedCallback(OnTrackablesUpdated);
}
private void OnVuforiaStarted()
{
// Try register camera image format
if (CameraDevice.Instance.SetFrameFormat(mPixelFormat, true))
{
Debug.Log("Successfully registered pixel format " + mPixelFormat.ToString());
mFormatRegistered = true;
}
else
{
Debug.LogError("Failed to register pixel format " + mPixelFormat.ToString() +
"\n the format may be unsupported by your device;" +
"\n consider using a different pixel format.");
mFormatRegistered = false;
}
}
private void OnPause(bool paused)
{
if (paused)
{
Debug.Log("App was paused");
UnregisterFormat();
}
else
{
Debug.Log("App was resumed");
RegisterFormat();
}
}
private void OnTrackablesUpdated()
{
//skip if still loading image to texture2d
if (LoadingTexture) return;
if (mFormatRegistered)
{
if (mAccessCameraImage)
{
Vuforia.Image image = CameraDevice.Instance.GetCameraImage(mPixelFormat);
//if (image != null && image.IsValid())
if (image != null)
{
byte[] pixels = image.Pixels;
int width = image.Width;
int height = image.Height;
StartCoroutine(SetTexture(pixels, width, height));
}
}
}
}
bool LoadingTexture = false;
IEnumerator SetTexture(byte[] pixels, int width, int height)
{
if (!LoadingTexture)
{
LoadingTexture = true;
if (pixels != null && pixels.Length > 0)
{
if (texture.width != width || texture.height != height)
{
#if UNITY_EDITOR
texture = new Texture2D(width, height, TextureFormat.R8, false);
#else
texture = new Texture2D(width, height, TextureFormat.RGB24, false);
#endif
}
texture.LoadRawTextureData(pixels);
texture.Apply();
if (rawImage != null)
{
rawImage.texture = texture;
rawImage.material.mainTexture = texture;
}
if (Mesh != null) Mesh.GetComponent<Renderer>().material.mainTexture = texture;
}
yield return null;
LoadingTexture = false;
}
}
private void UnregisterFormat()
{
Debug.Log("Unregistering camera pixel format " + mPixelFormat.ToString());
CameraDevice.Instance.SetFrameFormat(mPixelFormat, false);
mFormatRegistered = false;
}
private void RegisterFormat()
{
if (CameraDevice.Instance.SetFrameFormat(mPixelFormat, true))
{
Debug.Log("Successfully registered camera pixel format " + mPixelFormat.ToString());
mFormatRegistered = true;
}
else
{
Debug.LogError("Failed to register camera pixel format " + mPixelFormat.ToString());
mFormatRegistered = false;
}
}
}

Stop static mesh from moving with camera

I am trying to move the camera in the character class viewport. Whenever I hit 'play', the static mesh has repositioned itself almost as if its parented to the camera. So if I move the camera along the z axis, the mesh will not move but when I hit play it will have replaced itself to the relative position it was underneath the camera before I moved the camera component.
In other words, I am trying to unlink the movement between the two components.
I'm not sure how to disable this.
Here is my code for the character class.
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#include "ZombieShooterCharacter.h"
#include "ZombieShooterProjectile.h"
#include "Animation/AnimInstance.h"
#include "Camera/CameraComponent.h"
#include "Components/CapsuleComponent.h"
#include "Components/InputComponent.h"
#include "GameFramework/InputSettings.h"
#include "HeadMountedDisplayFunctionLibrary.h"
#include "Kismet/GameplayStatics.h"
#include "MotionControllerComponent.h"
#include "XRMotionControllerBase.h" // for FXRMotionControllerBase::RightHandSourceId
DEFINE_LOG_CATEGORY_STATIC(LogFPChar, Warning, All);
//////////////////////////////////////////////////////////////////////////
// AZombieShooterCharacter
AZombieShooterCharacter::AZombieShooterCharacter()
{
// Set size for collision capsule
GetCapsuleComponent()->InitCapsuleSize(55.f, 96.0f);
// set our turn rates for input
BaseTurnRate = 45.f;
BaseLookUpRate = 45.f;
// Create a CameraComponent
FirstPersonCameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("FirstPersonCamera"));
FirstPersonCameraComponent->SetupAttachment(GetCapsuleComponent());
FirstPersonCameraComponent->RelativeLocation = FVector(-39.56f, 1.75f, 64.f); // Position the camera
FirstPersonCameraComponent->bUsePawnControlRotation = true;
// Create a mesh component that will be used when being viewed from a '1st person' view (when controlling this pawn)
Mesh1P = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("CharacterMesh1P"));
Mesh1P->SetOnlyOwnerSee(true);
Mesh1P->SetupAttachment(FirstPersonCameraComponent);
Mesh1P->SetupAttachment(GetCapsuleComponent());
Mesh1P->bCastDynamicShadow = false;
Mesh1P->CastShadow = false;
Mesh1P->RelativeRotation = FRotator(1.9f, -19.19f, 5.2f);
Mesh1P->RelativeLocation = FVector(-0.5f, -4.4f, -155.7f);
// Create a gun mesh component
FP_Gun = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("FP_Gun"));
FP_Gun->SetOnlyOwnerSee(true); // only the owning player will see this mesh
FP_Gun->bCastDynamicShadow = false;
FP_Gun->CastShadow = false;
// FP_Gun->SetupAttachment(Mesh1P, TEXT("GripPoint"));
FP_Gun->SetupAttachment(RootComponent);
FP_MuzzleLocation = CreateDefaultSubobject<USceneComponent>(TEXT("MuzzleLocation"));
FP_MuzzleLocation->SetupAttachment(FP_Gun);
FP_MuzzleLocation->SetRelativeLocation(FVector(0.2f, 48.4f, -10.6f));
// Default offset from the character location for projectiles to spawn
GunOffset = FVector(100.0f, 0.0f, 10.0f);
// Note: The ProjectileClass and the skeletal mesh/anim blueprints for Mesh1P, FP_Gun, and VR_Gun
// are set in the derived blueprint asset named MyCharacter to avoid direct content references in C++.
}
void AZombieShooterCharacter::BeginPlay()
{
// Call the base class
Super::BeginPlay();
//Attach gun mesh component to Skeleton, doing it here because the skeleton is not yet created in the constructor
FP_Gun->AttachToComponent(Mesh1P, FAttachmentTransformRules(EAttachmentRule::SnapToTarget, true), TEXT("GripPoint"));
}
//////////////////////////////////////////////////////////////////////////
// Input
void AZombieShooterCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
{
// set up gameplay key bindings
check(PlayerInputComponent);
// Bind jump events
PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump);
PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping);
// Bind fire event
PlayerInputComponent->BindAction("Fire", IE_Pressed, this, &AZombieShooterCharacter::OnFire);
// Bind movement events
PlayerInputComponent->BindAxis("MoveForward", this, &AZombieShooterCharacter::MoveForward);
PlayerInputComponent->BindAxis("MoveRight", this, &AZombieShooterCharacter::MoveRight);
// We have 2 versions of the rotation bindings to handle different kinds of devices differently
// "turn" handles devices that provide an absolute delta, such as a mouse.
// "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick
PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput);
PlayerInputComponent->BindAxis("TurnRate", this, &AZombieShooterCharacter::TurnAtRate);
PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput);
PlayerInputComponent->BindAxis("LookUpRate", this, &AZombieShooterCharacter::LookUpAtRate);
}
void AZombieShooterCharacter::OnFire()
{
// try and fire a projectile
if (ProjectileClass != NULL)
{
UWorld* const World = GetWorld();
if (World != NULL)
{
const FRotator SpawnRotation = GetControlRotation();
// MuzzleOffset is in camera space, so transform it to world space before offsetting from the character location to find the final muzzle position
const FVector SpawnLocation = ((FP_MuzzleLocation != nullptr) ? FP_MuzzleLocation->GetComponentLocation() : GetActorLocation()) + SpawnRotation.RotateVector(GunOffset);
//Set Spawn Collision Handling Override
FActorSpawnParameters ActorSpawnParams;
ActorSpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButDontSpawnIfColliding;
// spawn the projectile at the muzzle
World->SpawnActor<AZombieShooterProjectile>(ProjectileClass, SpawnLocation, SpawnRotation, ActorSpawnParams);
}
}
// try and play the sound if specified
if (FireSound != NULL)
{
UGameplayStatics::PlaySoundAtLocation(this, FireSound, GetActorLocation());
}
// try and play a firing animation if specified
if (FireAnimation != NULL)
{
// Get the animation object for the arms mesh
UAnimInstance* AnimInstance = Mesh1P->GetAnimInstance();
if (AnimInstance != NULL)
{
AnimInstance->Montage_Play(FireAnimation, 1.f);
}
}
}
//Commenting this section out to be consistent with FPS BP template.
//This allows the user to turn without using the right virtual joystick
//void AZombieShooterCharacter::TouchUpdate(const ETouchIndex::Type FingerIndex, const FVector Location)
//{
// if ((TouchItem.bIsPressed == true) && (TouchItem.FingerIndex == FingerIndex))
// {
// if (TouchItem.bIsPressed)
// {
// if (GetWorld() != nullptr)
// {
// UGameViewportClient* ViewportClient = GetWorld()->GetGameViewport();
// if (ViewportClient != nullptr)
// {
// FVector MoveDelta = Location - TouchItem.Location;
// FVector2D ScreenSize;
// ViewportClient->GetViewportSize(ScreenSize);
// FVector2D ScaledDelta = FVector2D(MoveDelta.X, MoveDelta.Y) / ScreenSize;
// if (FMath::Abs(ScaledDelta.X) >= 4.0 / ScreenSize.X)
// {
// TouchItem.bMoved = true;
// float Value = ScaledDelta.X * BaseTurnRate;
// AddControllerYawInput(Value);
// }
// if (FMath::Abs(ScaledDelta.Y) >= 4.0 / ScreenSize.Y)
// {
// TouchItem.bMoved = true;
// float Value = ScaledDelta.Y * BaseTurnRate;
// AddControllerPitchInput(Value);
// }
// TouchItem.Location = Location;
// }
// TouchItem.Location = Location;
// }
// }
// }
//}
void AZombieShooterCharacter::MoveForward(float Value)
{
if (Value != 0.0f)
{
// add movement in that direction
AddMovementInput(GetActorForwardVector(), Value);
}
}
void AZombieShooterCharacter::MoveRight(float Value)
{
if (Value != 0.0f)
{
// add movement in that direction
AddMovementInput(GetActorRightVector(), Value);
}
}
void AZombieShooterCharacter::TurnAtRate(float Rate)
{
// calculate delta for this frame from the rate information
AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds());
}
void AZombieShooterCharacter::LookUpAtRate(float Rate)
{
// calculate delta for this frame from the rate information
AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds());
}
Thanks!
You're attaching the mesh to the camera. If you don't want to parent the two then remove this line:
Mesh1P->SetupAttachment(FirstPersonCameraComponent)
You should call SetupAttachment only once for each component

want to get screen point on render texture camera unity3d

I am making sniper game, I have 2 cameras, one is rendering whole environment, and second one is in scope of the gun, which has high zoom quality.
I am able to show, enemy point on screen through main camera. and it shows proper on main camera, but in scope camera(2nd camera), it not showing properly. I want to show these points exactly same as enemy is.
here is my script to show point so far. I am attaching screen shots, first one is for scope camera and does not showing proper place, and 2nd one is for main camera, showing at proper place (Red circle is pointing)
using UnityEngine;
using UnityEngine.UI;
public class identity_shower : MonoBehaviour {
public Texture tex;
public GameObject helt;
public bool target_is_high =false;
private int counter_for_high = -1;
private int counter_for_low = -1;
private int counter_value = 50;
private bool bool_for_high = false;
private bool bool_for_low = false;
private Camera scope_cam_active;
private RectTransform rectTransform;
private Vector2 uiOFFset;
// Update is called once per frame
void OnGUI()
{
GameObject[] objs = GameObject.FindGameObjectsWithTag("enemy_soldier");
if( objs.Length<=0 )
{
return;
}
if (bool_for_high)
{
Vector2 pos_to_display = Camera.main.WorldToScreenPoint (this.transform.position);
GUI.DrawTexture (new Rect(pos_to_display.x-10.0f,(Screen.height- pos_to_display.y)-40.0f,15,15),tex);
}
}
public void show_your_identity()
{
if (target_is_high) {
if (counter_for_high >= counter_value)
{
return;
}
counter_for_high = counter_for_high + 1;
if (counter_for_high >= counter_value)
{
bool_for_high = true;
}
} else if(!target_is_high)
{
if (counter_for_low >= counter_value)
{
return;
}
counter_for_low = counter_for_low + 1;
if (counter_for_low >= counter_value)
{
bool_for_low = true;
}
}
}
}

Create effect dark and light when game start in unity

I am new in unity, i need to create a effect when my game is started:
When game is being started, game scene is dark
When game has already been started, game scene is light.
Please teach me how i can do it, Thanks so much.
1st you have to add Light on your scene from GameObject Menu in unity. If you need On Off that light just add the Javascript to your light. Lot of ways to do this Google it and easy to find.
var times : float;
function Start () {
light.intensity =0;
}
function Update () {
times += Time.deltaTime; // just I added time.
if (times > 5) // or Here you can use Press key events....
light.intensity =8;
}
Here's what I use. I create a pixel texture and use the GUI system to ensure it'll be drawn before everything in the scene. I actually use a display manager to control the order GUI elements are drawn to make sure the overlay is in front of other gui elements.
using UnityEngine;
using System.Collections;
public class Overlay : MonoBehaviour {
//----------------------------------------------------------------------------------------------------//
[SerializeField]
private Color screenColor = Color.black;
[SerializeField]
private float fadeSpeed = 0.5f;
//----------------------------------------------------------------------------------------------------//
static private Texture2D overlay;
static private bool fadeOverlay;
static private bool fadeOverlayIn;
//----------------------------------------------------------------------------------------------------//
public void Awake() {
//Setup the values for the fading overlay.
overlay = new Texture2D( 1, 1 );
overlay.SetPixel( 0, 0, screenColor );
overlay.Apply();
fadeOverlay = true;
fadeOverlayIn = false;
}
public void Update() {
if ( fadeOverlay ) {
if ( fadeOverlayIn ) {
screenColor.a += Time.deltaTime * fadeSpeed;
if ( screenColor.a >= 1 ) {
fadeOverlay = false;
}
} else {
screenColor.a -= Time.deltaTime * fadeSpeed;
if ( screenColor.a <= 0 ) {
fadeOverlay = false;
}
}
overlay.SetPixel( 0, 0, screenColor );
overlay.Apply();
}
}
public void OnGUI() {
if ( fadeOverlayIn || fadeOverlay ) {
GUI.DrawTexture( Camera.main.pixelRect, overlay );
}
}
static public void Toggle() {
fadeOverlay = true;
fadeOverlayIn = !fadeOverlayIn;
}
//----------------------------------------------------------------------------------------------------//
}